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

   可以直接获取不用读配置文件
  1. #include <string.h>
  2. #include <sys/socket.h>
  3. #include <net/if.h>
  4. #include <sys/ioctl.h>
  5. #include <netinet/in.h>
  6. #include <stdio.h>
  7. int main()
  8. {
  9.         int inet_sock;
  10.         struct ifreq ifr;
  11.         char    ip[16];
  12.         struct sockaddr_in *sin = NULL;
  13.         memset(&ifr,0,sizeof(struct ifreq));
  14.         inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
  15.         strcpy(ifr.ifr_name, "eth0");
  16.         if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
  17.                 perror("ioctl");
  18.         memset(ip,0,sizeof(ip));
  19.         sin = (struct sockaddr_in*) &ifr.ifr_addr;
  20.         inet_ntop(AF_INET, &sin->sin_addr.s_addr, ip, 16);
  21.         printf("%s\n", ip);

  22.         return 0;
  23. }
复制代码

作者: kyleqian3008    时间: 2013-08-15 13:48
回复 3# myworkstation


    非常感谢,完全可用!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2