C language——read ip address in linux



点击(此处)折叠或打开

  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 ", getipaddress("enp13s0"));
  38.     printf("%u ", ip2uint(getipaddress("enp13s0")));
  39.     return 0;
  40. }

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



<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(129) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/ztguang/p/12649497.html