Qt應用層獲取網路連線狀態

2021-10-02 23:04:10 字數 1806 閱讀 2301

背景:專案需要實時監測網線的插拔狀態,方法有很多,分為兩大塊。

輪詢:可以輪詢cat /sys/class/net/eth0/carrier的值,連線時為1,斷開時為0。或者輪詢使用shell檢視ifconfig中對應網絡卡的狀態是否running,但是輪詢的方法非常耗費資源,需要開啟乙個全域性定時器。

使用netlink與核心互動,獲取驅動上報的狀態,此程式僅在應用層,前提是核心已有netlink的驅動。

.h

#include class netlinkmonitor:public qthread

return m_pinstance;

}private:

explicit netlinkmonitor(qobject *parent = nullptr);

static a7netlinkmonitor *m_pinstance ;

};

.cpp

#include "netlinkmonitor.h"

#include "configfile.h"

#include #include #include #include #include #include #include #include #include #include #include #include #define buflen 20480

#define network_type_usb "usb0"

#define network_type_eth "eth0"

a7netlinkmonitor *netlinkmonitor::m_pinstance = nullptr;

a7netlinkmonitor::netlinkmonitor(qobject *parent):qthread(parent)

void netlinkmonitor::run()

; int len = buflen;

struct sockaddr_nl addr;

struct nlmsghdr *nh;

struct ifinfomsg *ifinfo;

struct rtattr *attr;

fd = socket(af_netlink, sock_raw, netlink_route);

setsockopt(fd, sol_socket, so_rcvbuf, &len, sizeof(len));

memset(&addr, 0, sizeof(addr));

addr.nl_family = af_netlink;

addr.nl_groups = rtnlgrp_link;

bind(fd, (struct sockaddr*)&addr, sizeof(addr));

while ((retval = read(fd, buf, buflen)) > 0)

}//printf("\n");

sysconfig networkconfigwrite;

if(!strcmp((char*)rta_data(attr), network_type_usb))else

networkconfigwrite.setvalue("usb/status",(ifinfo->ifi_flags & iff_lower_up));

}if(!strcmp((char*)rta_data(attr), network_type_eth))else

networkconfigwrite.setvalue("lan/status",(ifinfo->ifi_flags & iff_lower_up));}}

}}

Android網路連線狀態

實習告一段落,回校準備畢業答辯,享受最後的大學生活。開發android應用程式,在需要進行連線網路時,如果沒有可用的網路連線,提醒手機使用者沒有可用的連連線,讓使用者有比較好的體驗。驗證 如下 1 首先獲得所有的網路連線manager.getallnetworkinfo 2 在迴圈判斷網路連線是否可...

網路基礎 應用層

應用層 解決如何使用 響應狀態碼 http常見header content type 資料型別 text html等 content length body的 長度 host 客戶端告知伺服器,所請求的資源是在哪個主機的哪個端 口上 user agent 宣告 使用者的作業系統和瀏覽器版本資訊 re...

網路協議 應用層

基於tcp ip的應用層協議 1.1.1 請求行 1.1.2 首部 就是請求頭,例如accept charset content type cache control if modified since 1.1.3 正文實體 正式的資料報文 1.1.4 http請求的傳送 客戶端傳送請求,應用層傳二...