本文使用getifaddrs 函式獲取網絡卡的ip和mac位址。getifaddrs函式有個特點,就是獲取位址時以鍊錶方式返回,且每個鍊錶節點要麼是ip,要麼是mac,所以如果要將網絡卡的ip和mac位址同時返回的話,需要對對返回鍊錶進行查詢和重新組合。本文實現目的,在於以網絡卡名方式返回ip和mac位址。**如下:
#ifndef _mylib_h
#define _mylib_h
#include #include #define error_report(msg) \
do while (0)
//clean the stdin cach
void clean_cach (void);
//get a string from stdin
int getstring (char *str, int num);
/* define a get if info struct */
struct if_ipv4_info ;
#endif
函式實現
#include #include #include #include #include #include #include #include #include #include #include #include #include #include "mylib.h"
#define debug 0
struct if_ipv4_info *if_info = null;
/*** add ip to a linklist
*/static int add_to_link (struct ifaddrs *ifap, char *buf)
strcpy (if_info->if_name, ifap->ifa_name);
switch (ifap->ifa_addr->sa_family) //switch
}else
}if (p != null) //switch
} else
strcpy (p->if_name, ifap->ifa_name);
switch (ifap->ifa_addr->sa_family)
q->next = p;
}//else
} return 0;
}int prt_if_info (struct sockaddr *ifa_addr, char *addrbuf, int bufsize)
break;
default:
ret = -1;
break;
} return ret;
}int get_if_info (void)
char buf[20];
for (ifap = ifa; ifap != null; ifap = ifap->ifa_next)
if (ifap->ifa_addr == null)
continue; /* if addr is null, this must be no ip address */
if (prt_if_info (ifap->ifa_addr, buf, 20) == 0)
} /* printf all of them */
struct if_ipv4_info *p = null;
for (p = if_info; p != null; p = p->next)
/* free link list */
struct if_ipv4_info *q = null;
for (p = if_info; p != null; )
freeifaddrs (ifa);
return 0;}/*
** test code
*/int main (int argc, char **argv)
在gcc version 4.7.2 20121109 (red hat 4.7.2-8) (gcc)編譯通過,執行效果如下
linux獲取本機網絡卡ip位址
include include include include include include include include include define eth name eth0 int main strncpy ifr.ifr name,eth name,ifnamsiz ifr.ifr n...
網絡卡不能獲取IP
前幾天,新買電腦的網絡卡不能獲取ip。開始以為是驅動的問題,後來去華碩中文論壇裡求教,安裝了驅動,解決了乙個裝置無法識別的現象,似乎當時網絡卡也能獲取ip了。但隨後不久,不能獲取ip的現象又經常出現。究竟是怎麼回事?這次經過仔細觀察,發現是無線路由器惹的禍。這台無線路由器是連線在辦公室的乙個交換機上...
多網絡卡下獲取本機IP的方式。
多網絡卡下獲取本機ip的方式。方式一 public class networkutils catch socketexception e log.error 獲取本地ip 失敗 e return localhostip 方式二 private static string getinetaddress...