獲取本機ip(有問題版)

想寫一個獲取本機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,遲點試一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章