我正在尝试获取我的服务器的 IP 地址,但它得到的是 127.0.1.1 而不是 127.0.0.1。错误在哪里?另外,我怎样才能获得真实的 IP 地址,而不是本地主机地址。
#define MAXHOSTNAME 256
#define DEBUG
char * getIPAddress()
{
char myname[ MAXHOSTNAME + 1 ];
static char IPinASCII[ MAXHOSTNAME ]; /* Oversized */
struct hostent * hp;
memset( myname, 0, MAXHOSTNAME + 1 ); /* Init */
memset( IPinASCII, 0, MAXHOSTNAME );
gethostname( myname, MAXHOSTNAME );
#ifdef DEBUG
printf( "hostname is %s\n", myname );
#endif /* DEBUG */
hp = gethostbyname( myname );
if( hp == NULL )
{
perror( "gethostbyname" );
return( "IP not found" );
}
inet_ntop( hp->h_addrtype, hp->h_addr_list[ 0 ], IPinASCII,
MAXHOSTNAME ) ;
#ifdef DEBUG
printf( "canonical hostname is %s at IP %s\n", hp->h_name, IPinASCII );
#endif /* DEBUG */
return( IPinASCII );
}
user@user-desktop:~/Desktop/My Code$ ./ipprint hostname is user-desktop canonical hostname is user-desktop at IP 127.0.1.1 127.0.1.1