C语言获取本机的第一个本地ip地址
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
/**
* Local IP address
*
* @param buf - buffer to take ip address
* @param len - length of buffer
*/
char *local_ip( char *buf, int len )
{
char hn[256];
struct hostent *he;
if( gethostname( hn, sizeof( hn ) ) )
return NULL;
if( !(he = gethostbyname( hn )) )
return NULL;
strncpy(
buf,
inet_ntoa( *((struct in_addr *)*he->h_addr_list) ),
len );
return buf;
}
