Linux c 檢測當前網卡是否已經啟動

来源:https://www.cnblogs.com/hylife/archive/2022/05/27/16316431.html
-Advertisement-
Play Games

思路: 1、socket 建立一個數據報套接字。 2、定義一個struct ifreq ifr 結構體。將網路名稱如“eth0” 賦值給ifr結構體的ifr.ifr_name。 3、調用ioctl(sockfd, SIOCGIFFLAGS, &ifr) 獲取網路標識。 如需設置網路標識,更改ifr結 ...


思路:

  1、socket 建立一個數據報套接字。

       2、定義一個struct ifreq ifr 結構體。將網路名稱如“eth0” 賦值給ifr結構體的ifr.ifr_name。

       3、調用ioctl(sockfd, SIOCGIFFLAGS, &ifr) 獲取網路標識。

如需設置網路標識,更改ifr結構體調用ioctl(sockfd, SIOCSIFFLAGS, &ifr) 進行設置。

       4、比對網路標識來確定網路是否正在運行。ifr.ifr_ifru.ifru_flags &IFF_RUNNING。

 

int GetNetStatus(const char *ifname)
{
    struct ifreq ifr;
    int sockfd;

    if((sockfd = Socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        printf("socket create error!\n");
        return - 1;
    }

    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

    if(ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0)
    {
        Close(sockfd);
        return - 1;
    }
    Close(sockfd);
    if(ifr.ifr_ifru.ifru_flags &IFF_RUNNING)
    {
        return 1;
    }
    else
    {
        return 0;
    }
   
}

 

struct ifreq 結構體的詳細介紹可參考。

struct ifreq學習和實例 - 走看看 (zoukankan.com)

 這個結構定義在/usr/include/net/if.h,用來配置和獲取ip地址,掩碼,MTU等介面信息的。


/* Interface request structure used for socket ioctl's. All interface
ioctl's must have parameter definitions which begin with ifr_name.
The remainder may be interface specific. */

struct ifreq
{
# define IFHWADDRLEN 6
# define IFNAMSIZ IF_NAMESIZE
union
{
char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
} ifr_ifrn;

union
{
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short int ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct ifmap ifru_map;
char ifru_slave[IFNAMSIZ]; /* Just fits the size */
char ifru_newname[IFNAMSIZ];
__caddr_t ifru_data;
} ifr_ifru;
};
# define ifr_name ifr_ifrn.ifrn_name /* interface name */
# define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */
# define ifr_addr ifr_ifru.ifru_addr /* address */
# define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-p lnk */
# define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
# define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */
# define ifr_flags ifr_ifru.ifru_flags /* flags */
# define ifr_metric ifr_ifru.ifru_ivalue /* metric */
# define ifr_mtu ifr_ifru.ifru_mtu /* mtu */
# define ifr_map ifr_ifru.ifru_map /* device map */
# define ifr_slave ifr_ifru.ifru_slave /* slave device */
# define ifr_data ifr_ifru.ifru_data /* for use by interface */
# define ifr_ifindex ifr_ifru.ifru_ivalue /* interface index */
# define ifr_bandwidth ifr_ifru.ifru_ivalue /* link bandwidth */
# define ifr_qlen ifr_ifru.ifru_ivalue /* queue length */
# define ifr_newname ifr_ifru.ifru_newname /* New name */
# define _IOT_ifreq _IOT(_IOTS(char),IFNAMSIZ,_IOTS(char),16,0,0)
# define _IOT_ifreq_short _IOT(_IOTS(char),IFNAMSIZ,_IOTS(short),1,0,0)
# define _IOT_ifreq_int _IOT(_IOTS(char),IFNAMSIZ,_IOTS(int),1,0,0)

 

 

 

 

 

實例一,獲取網卡的IP地址:
#include &lt;string.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;sys/ioctl.h&gt;
#include &lt;net/if.h&gt;
#include &lt;stdio.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;arpa/inet.h&gt;
int main()
{
int inet_sock;
struct ifreq ifr;
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);

strcpy(ifr.ifr_name, "eth0");
//SIOCGIFADDR標誌代表獲取介面地址
if (ioctl(inet_sock, SIOCGIFADDR, &amp;ifr) &lt; 0)
perror("ioctl");
printf("%s
", inet_ntoa(((struct sockaddr_in*)&amp;(ifr.ifr_addr))-&gt;sin_addr));
return 0;
}
實例二,實現簡單ifconfig功能:
/**
* file getifstat.c
* author wzj
* rief 訪問這個struct ifconf 修改,查詢狀態
* version
*
ote
* date: 2012年08月11日星期六22:55:25
*/
#include &lt;net/if.h&gt; /* for ifconf */
#include &lt;linux/sockios.h&gt; /* for net status mask */
#include &lt;netinet/in.h&gt; /* for sockaddr_in */
#include &lt;sys/socket.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/ioctl.h&gt;
#include &lt;stdio.h&gt;

#define MAX_INTERFACE (16)

void port_status(unsigned int flags);

/* set == 0: do clean , set == 1: do set! */
int set_if_flags(char *pif_name, int sock, int status, int set)
{
struct ifreq ifr;
int ret = 0;

strncpy(ifr.ifr_name, pif_name, strlen(pif_name) + 1);
ret = ioctl(sock, SIOCGIFFLAGS, &amp;ifr);
if(ret)
return -1;
/* set or clean */
if(set)
ifr.ifr_flags |= status;
else
ifr.ifr_flags &amp;= ~status;
/* set flags */
ret = ioctl(sock, SIOCSIFFLAGS, &amp;ifr);
if(ret)
return -1;

return 0;
}

int get_if_info(int fd)
{
struct ifreq buf[MAX_INTERFACE];
struct ifconf ifc;
int ret = 0;
int if_num = 0;

ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t) buf;

ret = ioctl(fd, SIOCGIFCONF, (char*)&amp;ifc);
if(ret)
{
printf("get if config info failed");
return -1;
}
/* 網口總數 ifc.ifc_len 應該是一個出入參數 */
if_num = ifc.ifc_len/sizeof(struct ifreq);
printf("interface num is interface = %d
", if_num);
while(if_num-- &gt; 0)
{
printf("net device: %s
", buf[if_num].ifr_name);
/* 獲取第n個網口信息 */
ret = ioctl(fd, SIOCGIFFLAGS, (char*)&amp;buf[if_num]);
if(ret)
continue;

/* 獲取網口狀態 */
port_status(buf[if_num].ifr_flags);

/* 獲取當前網卡的ip地址 */
ret = ioctl(fd, SIOCGIFADDR, (char*)&amp;buf[if_num]);
if(ret)
continue;
printf("IP address is:
%s
", inet_ntoa(((struct sockaddr_in *)(&amp;buf[if_num].ifr_addr))-&gt;sin_addr));

/* 獲取當前網卡的mac */
ret = ioctl(fd, SIOCGIFHWADDR, (char*)&amp;buf[if_num]);
if(ret)
continue;

printf("%02x:%02x:%02x:%02x:%02x:%02x

",
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[0],
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[1],
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[2],
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[3],
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[4],
(unsigned char)buf[if_num].ifr_hwaddr.sa_data[5]
);
}
}

void port_status(unsigned int flags)
{
if(flags &amp; IFF_UP)
{
printf("is up
");
}
if(flags &amp; IFF_BROADCAST)
{
printf("is broadcast
");
}
if(flags &amp; IFF_LOOPBACK)
{
printf("is loop back
");
}
if(flags &amp; IFF_POINTOPOINT)
{
printf("is point to point
");
}
if(flags &amp; IFF_RUNNING)
{
printf("is running
");
}
if(flags &amp; IFF_PROMISC)
{
printf("is promisc
");
}
}

int main()
{
int fd;

fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd &gt; 0)
{
get_if_info(fd);
close(fd);
}

return 0;
}
運行結果:
interface num is interface = 2
net device: eth0
is up
is broadcast
is running
IP address is:
192.168.100.200
54:be:f7:33:57:26
net device: lo
is up
is loop back
is running
IP address is:
127.0.0.1
00:00:00:00:00:00
參考轉載博客地址:
http://blog.csdn.net/dsg333/article/details/7525634
http://blog.csdn.net/kulung/article/details/6442597
http://blog.csdn.net/joker0910/article/details/7855998

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 0、重寫博文的原因 當初我的SpringBoot系列的知識是採用分節來寫的,即:每一個知識點為一篇博文,但是:最近我霉到家了,我發現有些博文神奇般地打不開了,害我去找當初的markdown筆記,但是方便的話還是線上版舒服,只要有網就可以訪問,因此昨天晚上東拼西湊搞出了這篇SpringBoot基礎系列 ...
  • 眾所周知,synchronized和Lock鎖是java併發編程中兩大利器,可以用來解決線程安全的問題。但是為什麼Java有了synchronized之後還是提供了Lock介面這個api,難道僅僅只是重覆造了輪子這麼簡單麽?本文就來探討一下這個問題。 談到這個問題,其實很多同學第一反應都會說,Loc ...
  • 當我們在寫一篇文章時,為了讓文章看起來不那麼沉悶無趣,通常我們會選擇在文章里添加有趣的圖片或者選擇圖片作為背景。那麼今天本文將通過C#/VB.NET來為大家詳細介紹如何設置圖片背景。只需短短幾步便可實現此功能。歡迎大家積极參与討論和交流分享。下麵是我整理的具體方法和步驟。 dll文件安裝(3種方法) ...
  • 轉載請註明來源 https://www.cnblogs.com/brucejiao/p/16188865.html 謝謝! 轉載請註明來源 https://www.cnblogs.com/brucejiao/p/16188865.html 謝謝! 轉載請註明來源 https://www.cnblog ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 本文介紹了在jenkins中maven的安裝及配置(安裝maven及jdk的方法),以及如何在jenkins中創建maven任務。 有三點需要註意的地方。 maven一定要安裝在jenkins伺服器上。 maven安裝之前要先安裝jdk。 建任務 ...
  • curl curl是一個非常實用的、用來與伺服器之間傳輸數據的工具;支持的協議包括 (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, S ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 1. 查看自己的網關地址 點擊虛擬機中編輯按鈕,選中虛擬網路編輯器 2.選擇點擊VMnet8,再點擊NAT設置 3.記住此時頁面的網關IP 4.進入虛擬機終端操作界面,切換到管理員用戶 5.找到CentOS8網路配置文件 cd /etc/sysc ...
  • 本文例子參考《STM32單片機開發實例——基於Proteus虛擬模擬與HAL/LL庫》 源代碼:https://github.com/LanLinnet/STM33F103R6 項目要求 掌握$I^2C$的通訊方法和時序,通過串口發送數據,單片機接收並存入AT24C02首地址中。按下按鍵BTN,單片 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...