Chinaunix

标题: linux C 获取IP [打印本页]

作者: liuhengloveyou    时间: 2010-02-25 08:59
标题: linux C 获取IP
本帖最后由 liuhengloveyou 于 2010-02-25 09:01 编辑
  1. #include <sys/socket.h>
  2. #include <unistd.h>
  3. #include <net/if.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <linux/sockios.h>
  7. #include <arpa/inet.h>

  8. #define BUFSIZE 16

  9. /*
  10. * 获得指定网口的IP
  11. */
  12. int get_inetip(char *in_name, char *buf)
  13. {   
  14.      int socket_fd;
  15.      struct ifreq ifr;
  16.      struct ifconf conf;

  17.      if ((socket_fd = socket(AF_INET,SOCK_DGRAM,0)) == -1) {
  18.           perror("socket error!\n");
  19.           return -1;
  20.      }

  21.      strcpy(ifr.ifr_name, in_name);
  22.   
  23.      if(ioctl(socket_fd,SIOCGIFADDR,&ifr) < 0) {
  24.           perror("ioctl error\n");
  25.           return -1;
  26.      }
  27.      
  28.      strcpy(buf, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr));

  29.      return 0;
  30. }



  31. int main(void)
  32. {
  33.      char buff[BUFSIZE];
  34.      get_inetip("eth0", buff);
  35.      printf("%s\n", buff);
  36.      
  37.      return 0;
  38. }

复制代码
昨天要这功能, 论坛里没找到很好的实现, 就自己实现了个. 比较简单.
作者: jjj137    时间: 2010-02-25 12:43
呵呵,每次用到时候都是去查 man ……
作者: wesleyluo    时间: 2010-03-11 17:03
我是来学习的。




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