2010-11-20 85 views

回答

2

網絡接口可以在sysfs/sys/class/net/eth[x]中看到。在那裏你可以檢查鏈接,界面狀態等等。

2

你可能要採取libudev的優勢來獲得/ SYS各地:

http://www.signal11.us/oss/udev/ 
1

我只是檢查,如果一個IP地址被分配給網卡。

您可以使用這樣的檢查,如果局域網是向上在給定的網絡卡(比如爲eth0):

/sbin/ifconfig eth0| grep 'inet addr:' | wc -l 

基於與否的IP地址是0或1本應該簡單地返回被分配給nic。

也可以使用Yann Ramin的方法列出所有網點的&執行檢查。


我錯過了注意到你正在尋找一個c代碼。也許添加標籤會很好。

無論哪種方式,我認爲你可以看看相同的文件(ifconfig)在c中手動讀取它的IP。

9

要檢查鏈接是否啓動,請嘗試類似這樣的操作。它沒有root權限。

#include <stdio.h>  // printf 
#include <string.h>  // strncpy 
//#include <sys/socket.h> // AF_INET 
#include <sys/ioctl.h> // SIOCGIFFLAGS 
#include <errno.h>  // errno 
#include <netinet/in.h> // IPPROTO_IP 
#include <net/if.h>  // IFF_*, ifreq 

#define ERROR(fmt, ...) do { printf(fmt, __VA_ARGS__); return -1; } while(0) 

int CheckLink(char *ifname) { 
    int state = -1; 
    int socId = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); 
    if (socId < 0) ERROR("Socket failed. Errno = %d\n", errno); 

    struct ifreq if_req; 
    (void) strncpy(if_req.ifr_name, ifname, sizeof(if_req.ifr_name)); 
    int rv = ioctl(socId, SIOCGIFFLAGS, &if_req); 
    close(socId); 

    if (rv == -1) ERROR("Ioctl failed. Errno = %d\n", errno); 

    return (if_req.ifr_flags & IFF_UP) && (if_req.ifr_flags & IFF_RUNNING); 
} 

int main() { 
    printf("%d\n", CheckLink("eth0")); 
} 

如果設置了IFF_UP,則表示接口已啓動(請參閱ifup)。如果IFF_RUNNING被設置,則接口被插入。 我也嘗試使用ethtool ioctl調用,但是當gid不是root時它失敗了。但只是爲了日誌:

... 
#include <asm/types.h>  // __u32 
#include <linux/ethtool.h> // ETHTOOL_GLINK 
#include <linux/sockios.h> // SIOCETHTOOL 
... 
int CheckLink(char *ifname) { 
    ... 
    struct ifreq if_req; 
    (void) strncpy(if_req.ifr_name, ifname, sizeof(if_req.ifr_name)); 

    struct ethtool_value edata; 
    edata.cmd = ETHTOOL_GLINK; 
    if_req.ifr_data = (char*) &edata; 

    int rv = ioctl(socId, SIOCETHTOOL, &if_req); 
    ... 

    return !!edata.data; 
} 
+0

@TrueY:一個問題,假設我只是想獲得鏈接的狀態通過ETHTOOL_GLINK與SIOCGIFFLAGS獲取它的區別是什麼? 'ethtool_value.data == 1'是否暗示'IFF_UP'和'IFF_RUNNING'。我在http://stackoverflow.com/questions/33039485/siocethtool-vs-siocgmiiphy-vs-siocgifflags上詢問了關於此的詳細問題。請讓我知道你的想法 – 2015-10-10 20:45:25

+0

@Vivek這是很久以前,但我認爲,如果edata.data == 1那麼接口是UP和RUNNING。 – TrueY 2015-10-11 21:09:22

1

由於這個問題有點重要,我會添加另一個答案,儘管它的極端年齡。您可以閱讀/ sys/class/net/eth0/operstate的內容,它只包含字符串「up \ n」或「down \ n」。

相關問題