Chinaunix首页 | 论坛 | 博客
  • 博客访问: 955789
  • 博文数量: 120
  • 博客积分: 6454
  • 博客等级: 准将
  • 技术积分: 1739
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-28 17:45
文章分类

全部博文(120)

文章存档

2014年(1)

2013年(1)

2012年(11)

2011年(16)

2010年(6)

2009年(11)

2008年(30)

2007年(44)

分类: C/C++

2012-08-01 18:22:45


点击(此处)折叠或打开

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

  8. long getlocalhostip ()
  9. {
  10.     int MAXINTERFACES = 16;
  11.     long ip;
  12.     int fd, intrface, retn = 0;
  13.     struct ifreq buf[MAXINTERFACES];
  14.     struct ifconf ifc;
  15.     ip = -1;
  16.     if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) {
  17.         ifc.ifc_len = sizeof buf;
  18.         ifc.ifc_buf = (caddr_t) buf;
  19.         if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {
  20.             intrface = ifc.ifc_len / sizeof (struct ifreq);
  21.             while (intrface-- > 0) {
  22.                 if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface]))) {
  23.                     ip = inet_addr (inet_ntoa (((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr));
  24.                     break;
  25.                 }
  26.             }
  27.         }
  28.         close (fd);
  29.     }
  30.     return ip;
  31. }

  32. union ipu
  33. {
  34.     long ip;
  35.     unsigned char ipchar[4];
  36. };

  37. int main (int argc, char **argv)
  38. {
  39.     union ipu localip;
  40.     localip.ip = getlocalhostip ();
  41.     printf ("local ip:%x :%u.%u.%u.%u \n", localip.ip, localip.ipchar[0], localip.ipchar[1], localip.ipchar[2], localip.ipchar[3]);
  42.     return 0;
  43. }

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