Chinaunix首页 | 论坛 | 博客
  • 博客访问: 862363
  • 博文数量: 286
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1841
  • 用 户 组: 普通用户
  • 注册时间: 2015-05-09 16:26
文章分类

全部博文(286)

文章存档

2016年(38)

2015年(248)

我的朋友

分类: LINUX

2015-07-31 21:10:46


点击(此处)折叠或打开

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

  10. unsigned char    g_eth_name[16];
  11. unsigned char    g_macaddr[6];
  12. unsigned int    g_subnetmask;
  13. unsigned int    g_ipaddr;
  14. unsigned int    g_broadcast_ipaddr;

  15. /*初始化网络,获取当前网络设备的信息*/
  16. void init_net(void)
  17. {
  18.     int i;
  19.     int sock;
  20.     struct sockaddr_in sin;
  21.     struct ifreq ifr;

  22.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  23.     if (sock == -1) {
  24.         perror("socket");
  25.     }
  26.     
  27.     strcpy(g_eth_name, "eth0");
  28.         strcpy(ifr.ifr_name, g_eth_name);
  29.     printf("eth name:\t%s\n", g_eth_name);


  30.     // 获取并打印网卡地址
  31.     if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
  32.         perror("ioctl");
  33.     }
  34.     memcpy(g_macaddr, ifr.ifr_hwaddr.sa_data, 6);

  35.     printf("local mac:\t");
  36.     for(i=0;i<5;i++) {
  37.         printf("%.2x:", g_macaddr[i]);
  38.     }
  39.     printf("%.2x\n",g_macaddr[i]);

  40.     // 获取并打印IP地址
  41.     if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) {
  42.         perror("ioctl");
  43.     }
  44.     g_ipaddr = sin.sin_addr.s_addr;
  45.     memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
  46.     printf("local eth0:\t%s\n", inet_ntoa(sin.sin_addr));

  47.     // 获取并打印广播地址
  48.     if (ioctl(sock, SIOCGIFBRDADDR, &ifr) < 0) {
  49.         perror("ioctl");
  50.     }
  51.     memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
  52.     g_broadcast_ipaddr = sin.sin_addr.s_addr;
  53.     printf("broadcast:\t%s\n", inet_ntoa(sin.sin_addr));

  54.     // 获取并打印子网掩码
  55.     if (ioctl(sock, SIOCGIFNETMASK, &ifr) < 0) {
  56.         perror("ioctl");
  57.     }
  58.     memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
  59.     g_subnetmask = sin.sin_addr.s_addr;
  60.     printf("subnetmask:\t%s\n", inet_ntoa(sin.sin_addr));

  61.     close(sock);
  62. }

  63. int main()
  64. {
  65.     /*initialize...*/
  66.     init_net();

  67.     /*do something*/

  68.     return 0;
  69. }
  70. /* result:
  71. eth name:    eth0
  72. local mac:    xx:xx:xx:xx:xxxx
  73. local eth0:    192.168.10.103
  74. broadcast:    192.168.10.255
  75. subnetmask:    255.255.255.0

  76. */


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