Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6544090
  • 博文数量: 1159
  • 博客积分: 12444
  • 博客等级: 上将
  • 技术积分: 12570
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-13 21:34
文章分类

全部博文(1159)

文章存档

2016年(126)

2015年(350)

2014年(56)

2013年(91)

2012年(182)

2011年(193)

2010年(138)

2009年(23)

分类: C/C++

2016-01-16 14:50:31



点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <sys/ioctl.h>
  7. #include <netinet/in.h>
  8. #include <net/if.h>
  9. #include <arpa/inet.h>

  10. //convert ip address string into uint
  11. uint32_t ip2uint(const char *ip) {
  12.     int a, b, c, d;
  13.     uint32_t addr = 0;

  14.     if (sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
  15.        return 0;

  16.     addr = a << 24;
  17.     addr |= b << 16;
  18.     addr |= c << 8;
  19.     addr |= d;
  20.     return addr;
  21. }

  22. //read ip address
  23. char * getipaddress(char * interface)
  24. {
  25.     int fd;
  26.     struct ifreq ifr;

  27.     fd = socket(AF_INET, SOCK_DGRAM, 0);
  28.     ifr.ifr_addr.sa_family = AF_INET;    //I want to get an IPv4 IP address
  29.     strncpy(ifr.ifr_name, interface, IFNAMSIZ - 1);    //I want IP address attached to "enp13s0"
  30.     ioctl(fd, SIOCGIFADDR, &ifr);
  31.     close(fd);
  32.     return inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
  33. }

  34. int main()
  35. {
  36.     /* display result */
  37.     printf("%s\n", getipaddress("enp13s0"));
  38.     printf("%u\n", ip2uint(getipaddress("enp13s0")));
  39.     return 0;
  40. }

[root@localhost 桌面]# gcc tmp.c -o tmp
[root@localhost 桌面]# ./tmp
10.108.162.227
174891747
[root@localhost 桌面]#



阅读(1069) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~