想写一个获取本机ip的程序:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
int main()
{
char ip[32];
struct hostent *hp;
struct in_addr in;
int num = 0;
char hostname[32];
gethostname(hostname, 31);
*ip = 0;
if((hp = gethostbyname(hostname)) == NULL)
{
printf("ERROR: unable get host '%s' ip\n", hostname);
return -1;
}
while(hp->h_addr_list[num] != NULL)
{
memcpy(&in.s_addr, hp->h_addr_list[num], sizeof(in.s_addr));
strcpy(ip, inet_ntoa(in));
printf("ip is %s\n", ip);
num++;
}
return 0;
}
结果编译运行后:
奇怪的是,为什么只有本地环回地址?现在暂时还没弄清楚,先记录一下。
在网上查了一下,可以用ioctl的SIOCGIFCONF方法获得接口IP,迟点试一下。