Chinaunix首页 | 论坛 | 博客
  • 博客访问: 798695
  • 博文数量: 124
  • 博客积分: 1927
  • 博客等级: 上尉
  • 技术积分: 932
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-31 14:06
文章分类

全部博文(124)

文章存档

2018年(5)

2017年(2)

2016年(6)

2015年(4)

2014年(24)

2013年(7)

2012年(11)

2011年(13)

2010年(52)

我的朋友

分类: LINUX

2013-09-02 10:24:00

原文地址:Linux获得本机的MAC地址 作者:frankzfz

#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <linux/sockios.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
int GetMac(const char *,unsigned char *);

int GetMac(const char *ifname,unsigned char *mac)
  {
    int sock,ret;
    struct ifreq ifr;
    sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock<0)
    {
      perror("socket error!\n");
      return -1;
    }

    memset(&ifr,0,sizeof(ifr));
    strcpy(ifr.ifr_name,ifname);
    ret = ioctl(sock,SIOCGIFHWADDR,&ifr,sizeof(ifr));
    if(ret == 0)
    {
      memcpy(mac,ifr.ifr_hwaddr.sa_data,6);
    }
    else
    {
      perror("ioctl error!\n");
    }
  close(sock);
    return ret;
  }
int main(int argc,char *argv[])
{int ret;
  char ifname[IFNAMSIZ];
  unsigned char mac[6];

  if(argc ==1)
  {
    strcpy(ifname,"eth1");//根据自己系统的不同,名字会有所不同,可是使用ifconfig,命令测试
  }
  else
  {
  strcpy(ifname,argv[1]);
  }
  memset(mac,0,sizeof(mac));
  ret = GetMac(ifname,mac);
  if(ret == 0)
  {
    printf("%s mac address is :[%02X:%02X:%02X:%02X:%02X:%02X]\n",ifname,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5] );
  }
  else
  {
    fprintf(stderr,"Can,t get %s's mac address\n",ifname);
  }
  return 0;
}


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