linux:
#include <linux/sockios.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <linux/if.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define ETHTOOL_GLINK 0x0000000a /* Get link status (ethtool_value) */ typedef enum { IFSTATUS_UP, IFSTATUS_DOWN, IFSTATUS_ERR } interface_status_t; typedef signed int u32; /* for passing single values */ struct ethtool_value { u32 cmd; u32 data; }; interface_status_t interface_detect_beat_ethtool(int fd, char *iface) { struct ifreq ifr; struct ethtool_value edata; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name)-1); edata.cmd = ETHTOOL_GLINK; ifr.ifr_data = (caddr_t) &edata; if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) { // perror("ETHTOOL_GLINK failed "); return IFSTATUS_ERR; } return edata.data ? IFSTATUS_UP : IFSTATUS_DOWN; } int main (int argc, char *argv[]) { FILE *fp; interface_status_t status; char buf[512] = {'\0'}; char hw_name[10] = {'\0'}; char *token = NULL; /* 獲取活動網卡名稱 */ int fd_eth; int interfaceNum = 0; struct ifreq buf_eth[16]; struct ifconf ifc_eth; struct ifreq ifrcopy_eth; if ((fd_eth = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); close(fd_eth); return -1; } ifc_eth.ifc_len = sizeof(buf_eth); ifc_eth.ifc_buf = (caddr_t)buf_eth; if (!ioctl(fd_eth, SIOCGIFCONF, (char *)&ifc_eth)) { interfaceNum = ifc_eth.ifc_len / sizeof(struct ifreq); // printf("interface num = %d\n", interfaceNum); while (interfaceNum-- > 0) { if(strstr(buf_eth[interfaceNum].ifr_name,"eth") != NULL) { printf("device name:@@@@@@@@@@@\n"); printf("device name: %s\n", buf_eth[interfaceNum].ifr_name); strncpy(hw_name,buf_eth[interfaceNum].ifr_name, strlen(buf_eth[interfaceNum].ifr_name)); } } } //判斷是否插入網線 int fd; if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket "); exit(0); } me/yckj/Desktop/linux上svn的使用.docx' status = interface_detect_beat_ethtool(fd, hw_name); close(fd); switch (status) { case IFSTATUS_UP: printf("%s : link up\n", hw_name); break; case IFSTATUS_DOWN: printf("%s : link up\n", hw_name); break; default: printf("Detect Error\n"); break; } return 0; }
windows:
#include <stdio.h> #include <Wininet.h> int net_link_check() { int ret; DWORD flags;//上網方式 BOOL m_bOnline = TRUE;//是否在線 m_bOnline=InternetGetConnectedState(&flags,0); if(m_bOnline)//在線 { printf("在線\n"); ret = 1; } else { printf("不在線\n"); ret = 0; } return ret; }
注:windows的代碼在編譯過程中可能會出現InternetGetConnectedState找不到定義的情況,時因爲gcc編譯時鏈接不到Wininet的庫,解決的方法是在Makefile文件中添加庫的鏈接 -lwininet.