Chinaunix
标题:
socket函数能不能获取制定网卡的IP地址?比如eth0
[打印本页]
作者:
kyleqian3008
时间:
2013-08-15 09:50
标题:
socket函数能不能获取制定网卡的IP地址?比如eth0
socket系列函数中能不能获取指定网卡的IP地址?我的机器有2个网卡,eth0,eth1, 我想获取其中一个配置的IP地址。
是不是只能读取某个配置文件?我记得不同发行版本中网络相关的配置文件差别挺大……
作者:
djsxut
时间:
2013-08-15 11:10
可以用脚本截取出来IP。
这个别人写的:
http://blog.csdn.net/hanzengyi/article/details/5983030
作者:
myworkstation
时间:
2013-08-15 11:22
回复
1#
kyleqian3008
可以直接获取不用读配置文件
#include <string.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <stdio.h>
int main()
{
int inet_sock;
struct ifreq ifr;
char ip[16];
struct sockaddr_in *sin = NULL;
memset(&ifr,0,sizeof(struct ifreq));
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, "eth0");
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
perror("ioctl");
memset(ip,0,sizeof(ip));
sin = (struct sockaddr_in*) &ifr.ifr_addr;
inet_ntop(AF_INET, &sin->sin_addr.s_addr, ip, 16);
printf("%s\n", ip);
return 0;
}
复制代码
作者:
kyleqian3008
时间:
2013-08-15 13:48
回复
3#
myworkstation
非常感谢,完全可用!
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2