当前位置: 技术问答>linux和unix
linux下怎麼可以得到本機的ip地址啊(用程序)?
来源: 互联网 发布时间:2015-05-20
本文导语: linux下怎麼可以得到本機的ip地址啊(用程序)?? | 实在不行,读/proc /proc/net/tcp 其中的local_address就是本机ip 不过要转换,具体函数是是是是……忘了 | 读 ifconfig 的代码可能有...
linux下怎麼可以得到本機的ip地址啊(用程序)??
|
实在不行,读/proc
/proc/net/tcp
其中的local_address就是本机ip
不过要转换,具体函数是是是是……忘了
/proc/net/tcp
其中的local_address就是本机ip
不过要转换,具体函数是是是是……忘了
|
读 ifconfig 的代码可能有用吧。
|
创建一个socket
然后用getsockname就可以了。
然后用getsockname就可以了。
|
本机可能会有多个IP,下面这段程序可以获得本机IP:
struct hostent *h;
char host[100];
int i;
gethostname(host, 100);
if ((h = gethostbyname(host)) == NULL) {
printf("Error : %s!n", hstrerror(h_errno));
return;
};
printf("Default IP: %sn", inet_ntoa (*((struct in_addr *)h->h_addr)));
for (i = 0; ih_length / sizeof(int); i++) {
printf("IP %d : %sn", i+1, inet_ntoa (*((struct in_addr *)h->h_addr_list[i])));
};
需要注意的是,h->h_addr实际上就是h->h_addr_list[0],是为了向前兼容而保留的。
DNS操作时的错误处理与普通程序不同,gethostbyname通过设置h_errno代表出错号,对应的错误函数有hstrerror()和herror(),分别对应于strerror()和perror()这两个普通的错误函数。
struct hostent *h;
char host[100];
int i;
gethostname(host, 100);
if ((h = gethostbyname(host)) == NULL) {
printf("Error : %s!n", hstrerror(h_errno));
return;
};
printf("Default IP: %sn", inet_ntoa (*((struct in_addr *)h->h_addr)));
for (i = 0; ih_length / sizeof(int); i++) {
printf("IP %d : %sn", i+1, inet_ntoa (*((struct in_addr *)h->h_addr_list[i])));
};
需要注意的是,h->h_addr实际上就是h->h_addr_list[0],是为了向前兼容而保留的。
DNS操作时的错误处理与普通程序不同,gethostbyname通过设置h_errno代表出错号,对应的错误函数有hstrerror()和herror(),分别对应于strerror()和perror()这两个普通的错误函数。