Chinaunix首页 | 论坛 | 博客
  • 博客访问: 758284
  • 博文数量: 144
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1150
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-17 14:32
个人简介

小公司研发总监,既当司令也当兵!

文章分类

全部博文(144)

分类: LINUX

2017-11-15 10:36:20


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <ifaddrs.h>

  10. int get_ip_mask(const char* ifname, struct sockaddr_in* addr, struct sockaddr_in* mask)
  11. {
  12.         struct ifaddrs *ifcs;
  13.         struct ifaddrs *ifc;

  14.         char ip[64] = {};
  15.         char nm[64] = {};
  16.         int ret = 1;

  17.         if(0 != getifaddrs(&ifcs))
  18.                 return -1;
  19.   
  20.         for(ifc = ifcs; NULL != ifc; ifc = ifc->ifa_next)
  21.         {
  22.                 if (strcmp(ifname, ifc->ifa_name))
  23.                 {
  24.                         continue;
  25.                 }
  26.                 if ((NULL != ifc->ifa_addr && ((struct sockaddr_in *)ifc->ifa_addr)->sin_addr.s_addr != 0)
  27.                     && (NULL != ifc->ifa_netmask && ((struct sockaddr_in *)ifc->ifa_netmask)->sin_addr.s_addr != 0) )
  28.                 {
  29.                         memcpy(addr, ifc->ifa_addr, sizeof(struct sockaddr_in));
  30.                         memcpy(mask, ifc->ifa_netmask, sizeof(struct sockaddr_in));
  31.                         ret = 0;
  32.                         break;
  33.                 }
  34.         }
  35.         freeifaddrs(ifcs);
  36.         return ret;
  37. }

  38. int main(int argc, char* argv[])
  39. {
  40.         struct sockaddr_in addr;
  41.         struct sockaddr_in mask;

  42.         if ( 0== get_ip_mask("eth0", &addr, &mask))
  43.         {
  44.                 printf("found 0x%x, 0x%x\n", addr.sin_addr.s_addr, mask.sin_addr.s_addr);
  45.         }
  46.     return 0;
  47. }

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