歡迎您光臨本站 註冊首頁

linux下檢測網卡與網線連通狀態

←手機掃碼閱讀     火星人 @ 2014-03-12 , reply:0
  作者:linuxeden管理團隊成員mgqw
   在linux下使用ifconfigl命令能很方便的查看網卡與網線是否連通,運行ifconfig eth0命令大致輸出如下:

# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:25:35:68:CC:D6 
          inet addr:192.168.1.168  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::215:c5ff:fe18:ccd6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:130722 errors:0 dropped:0 overruns:0 frame:0
          TX packets:112560 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:104371099 (99.5 MiB)  TX bytes:20518584 (19.5 MiB)
          Interrupt:16

其中的RUNNING就表示網卡與網線正常鏈接,拔掉網線再運行此命令就會發現RUNNING不在了。

    我的目的是用C語言來實現程序,而linux系統提供了popen/pclose進程管道讓C和shell很方便的交互,不過使用的時候要注意設置許可權,以免造成安全隱患。廢話不多說,看下面C代碼結合shell命令檢測網卡與網線連通狀況:
netstat.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/**********************************************************************
* 函數名稱: GetNetStat
* 功能描述: 檢測網路鏈接是否斷開
* 輸入參數:
* 輸出參數: 無
* 返 回 值: 正常鏈接1,斷開返回-1
* 其它說明: 本程序需要超級用戶許可權才能成功調用ifconfig命令
* 修改日期        版本號     修改人          修改內容
* ---------------------------------------------------------------------
* 2010/04/02      V1.0      eden_mgqw
***********************************************************************/
int GetNetStat( )
{
    char    buffer[BUFSIZ];
    FILE    *read_fp;
    int        chars_read;
    int        ret;
   
    memset( buffer, 0, BUFSIZ );
    read_fp = popen("ifconfig eth0 | grep RUNNING", "r");
    if ( read_fp != NULL )
    {
        chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
        if (chars_read > 0)
        {
            ret = 1;
        }
        else
        {
            ret = -1;
        }
        pclose(read_fp);
    }
    else
    {
        ret = -1;
    }

    return ret;
}


int main()
{
    int i=0;
    i = GetNetStat();
    printf( "\nNetStat = %d\n", i );
    return 0;
}


下面是編譯運行程序的輸出結果(正常返回1,斷開返回-1):
# cc netstat.c
# ./a.out
NetStat = 1

在此特別感謝linuxeden的shell區版主li-jiahuan帥鍋,為本文提供了shell支持-_-!
條條大路通羅馬,在CU上有位帥鍋用另外一種方法實現了這個功能,地址如下:
http://blog.chinaunix.net/u/12592/showart_1798479.html


[火星人 ] linux下檢測網卡與網線連通狀態已經有329次圍觀

http://coctec.com/docs/program/show-post-71587.html