因开发需要获取有线网卡的MAC地址,发现网上获取的方法多数只能获取联网网卡的MAC地址,因此重写了下Ubuntu10下测试通过.
下面代码无论网卡是否连线,都可以获取MAC地址,稍作修改,可以输出系统所有的网卡硬件MAC地址,无论是否已经联网.
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
-
- #include <sys/ioctl.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <linux/if.h>
-
- #define IFNAMSIZ 16
拥有帝国一切,皆有可能。欢迎访问phome.net
-
-
- char ifname_buf[2048];
- char *ifnames = ifname_buf;
- int count = 0;
-
- void add_interface_name(const char * name)
- {
- int i;
- for (i=0;i<count;i )
- {
- if (!strcmp(ifnames i*IFNAMSIZ, name))
- return;
- }
- strncpy(ifnames (count )*IFNAMSIZ, name, IFNAMSIZ-1);
- }
-
- char * get_name(char *name, char *p)
- {
- while (isspace(*p))
- p ;
- while (*p) {
- if (isspace(*p))
- break;
拥有帝国一切,皆有可能。欢迎访问phome.net- if (*p == '':'') {
- char *dot = p, *dotname = name;
- *name = *p ;
- while (isdigit(*p))
- *name = *p ;
- if (*p != '':'') {
- p = dot;
- name = dotname;
- }
- if (*p == '''')
- return NULL;
- p ;
- break;
- }
- *name = *p ;
- }
- *name = '''';
- return p;
- }
-
-
-
- int get_procnet_list()
- {
- FILE
拥有帝国一切,皆有可能。欢迎访问phome.net *fh;
- char buf[512];
- fh = fopen("/proc/net/dev", "r");
- if (!fh)
- return -1;
-
- fgets(buf, sizeof buf, fh);
- fgets(buf, sizeof buf, fh);
- while (fgets(buf, sizeof buf, fh))
- {
- char name[IFNAMSIZ];
- get_name(name, buf);
- add_interface_name(name);
- }
- fclose(fh);
- return 0;
- }
-
- long mac_addr_sys ( u_char *addr)
- {
-
- struct ifreq ifr;
- struct ifreq *IFR;
- struct ifconf ifc;
- char
拥有帝国一切,皆有可能。欢迎访问phome.net buf[1024];
- int s, i;
- int ok = 0;
-
-
- memset(ifname_buf, 0, sizeof(ifname_buf));
-
-
- s = socket(AF_INET, SOCK_DGRAM, 0);
- if (s==-1) {
- return -1;
- }
-
- ifc.ifc_len = sizeof(buf);
- ifc.ifc_buf = buf;
- ioctl(s, SIOCGIFCONF, &ifc);
-
- IFR = ifc.ifc_req;
-
- for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR ) {
- add_interface_name(IFR->ifr_name);
- }
-
- if (get_procnet_list())
- return -1;
-
-
- for (i = 0; i < count; i ) {
- strcpy(ifr.ifr_name, ifnames i*IFNAMSIZ);
- if (!strncmp(ifr.ifr_name, "eth", 3))
- if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
- if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
- if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
- char *p = (char *)ifr.ifr_hwaddr.sa_data;
- if (!*((int *)p) && !*((int *)(p 2)) )
- continue;
-
- ok = 1;
- break;
- }
- }
- }
- }
-
- close(s);
- if (ok) {
- bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
拥有帝国一切,皆有可能。欢迎访问phome.net
- printf( "n");
- }
- else {
- fprintf( stderr, "can''t get MAC addressn");
- exit( 1);
- }
- return 0;
- }
本文出自 “快乐的技术员” 博客,请务必保留此出处http://carltao.blog.51cto.com/856514/415119
拥有帝国一切,皆有可能。欢迎访问phome.net |