linux:

#include 
#include
#include
#include
#include
#include
#include
#include
#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 
#include
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.