Linux下獲取所有可用網絡卡資訊

2021-06-28 22:41:01 字數 1850 閱讀 3728

在linux

下開發網路程式時,經常會遇到需要取本地網路介面名、ip

、廣播位址

、子網掩碼或者mac位址等資訊的需求,最常見的辦法是配合巨集siocgifhwaddr、siocgifaddr、siocgifbrdaddr與siocgifnetmask作為引數呼叫函式

ioctl分別獲得mac位址、ip位址、廣播位址與子網掩碼來實現。一次性獲取此類資訊的c語言

**實現如下。     

#include

#include

#include

#include

#include

#include

intgetlocalinfo

(void);

charip[

32]=;

char

broadaddr[32

]=;char

subnetmask[32

]=;if

((fd

=socket

(af_inet

,sock_dgram,0

))<0)

ifc.

ifc_len

=sizeof

(buf

);ifc

.ifc_buf =(

caddr_t

)buf;if

(!ioctl(fd

,siocgifconf,(

char

*)&ifc

))//get the mac of this inte***ce

if(!

ioctl(fd

,siocgifhwaddr,(

char

*)(&

buf[

inte***cenum

])))

else

//get the ip of this inte***ce

if(!

ioctl(fd

,siocgifaddr,(

char

*)&buf

[inte***cenum

]))else

//get the broad address of this inte***ce

if(!

ioctl(fd

,siocgifbrdaddr,&

buf[

inte***cenum

]))else

//get the subnet mask of this inte***ce

if(!

ioctl(fd

,siocgifnetmask,&

buf[

inte***cenum

]))else}}

else

close(fd

);return0;

}int

main

(void

)

使用ioctl函式雖然可以獲取所有的資訊,但是使用起來比較麻煩,如果不需要獲取mac位址,那麼使用getifaddrs函式來獲取更加方便與簡潔。值得一提的是,在macos或ios

系統上(如iphone

程式開發),上述iotcl函式沒法獲得mac位址跟子網掩碼,這個使用,使用getifaddrs函式便更有優勢了。下面是使用getiaddrs函式獲取網絡卡資訊的c語言**實現。

#include

#include

#include

intgetsubnetmask()}

freeifaddrs

(iflist

);return0;

}int

main

(void

)

Linux下如何獲取網絡卡資訊

有時候,寫程式的時候需要獲取計算機的網路資訊,比如ip位址 電腦名稱 dns等資訊。ip位址和電腦名稱是比較容易獲取到的,而要想獲取位址掩碼 dns 閘道器等資訊就有些麻煩了。在windows下我們一般都是通過從登錄檔讀取這些資訊。在linux怎麼做呢?其實,linux下更加容易一些。因為我們可以拿...

Linux下獲取多網絡卡資訊

支援多網絡卡,主要是使用ioctl函式系統呼叫實現,通過指定裝置名實現指定功能.之前使用socket 函式,獲取檔案描述符.在此基礎可以很輕鬆的擴充套件,如獲取net mask,mac address等 include stdio.h include sys types.h include sys ...

linux 獲取網絡卡資訊

sar n dev 2 10 41 37 am iface rxpck s txpck s rxkb s txkb s rxcmp s txcmp s rxmcst s 10 41 39 am eth0 1.50 1648.00 0.15 117.54 0.00 0.00 1.00 10 41 39...