Chinaunix

标题: Linux网络套接字:获取网络参数 [打印本页]

作者: Mr小万    时间: 2016-05-22 12:35
标题: Linux网络套接字:获取网络参数
这篇帖子并没有写得太完整,包括获取ipv4地址,ipv6地址,是否处于混杂模式等会再稍后的博文中补全。

代码中会用到了一些宏定义
  1. #define Print(fmt, args...) printf("[%s, %d] "fmt"\n", __func__, __LINE__, ##args)
  2. #define MAC_ADDR_SIZE   6
复制代码
1、获取本地mac地址
  1. int get_mac_addr(int sockfd, char *devName, unsigned char *mac)
  2. {
  3.         struct ifreq ifr;

  4.         strncpy(ifr.ifr_name, devName, sizeof(ifr.ifr_name));
  5.         if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) < 0)
  6.         {
  7.                 Print("ioctl: %s", strerror(errno));
  8.                 return -1;
  9.         }

  10.         memcpy(mac, ifr.ifr_hwaddr.sa_data, MAC_ADDR_SIZE);

  11.         printf("%s mac:%02x:%02x:%02x:%02x:%02x:%02x\n",
  12.                 devName, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

  13.         return 0;
  14. }
复制代码
2、获取网络接口号
  1. int get_ifindex(int sockfd, char *devName)
  2. {
  3.         struct ifreq ifr;

  4.         strncpy(ifr.ifr_name, devName, sizeof(ifr.ifr_name));
  5.         if (ioctl(sockfd, SIOCGIFINDEX, &ifr) < 0)
  6.         {
  7.                 Print("ioctl: %s", strerror(errno));
  8.                 return -1;
  9.         }

  10.         printf("get ifindex: %d\n", ifr.ifr_ifindex);
  11.         return ifr.ifr_ifindex;
  12. }
复制代码





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