Linux下如何用C编程实现检测网卡与网线的连接状态
linux-dash
 A beautiful web dashboard for Linux
 项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
  免费下载资源
免费下载资源
       ·  
 http://www.caojunfei.com/?p=614
- int get_netportstatus(const char *interface) {
- char cmd[1024];
- char *tt;
- FILE *fp;
- int devflag;
- devflag=get_netflag(interface);
- if (devflag==DEV_DOWN) {
- sprintf(cmd,"ifconfig %s up",interface);
- system(cmd);
- }
- sprintf(cmd,"ethtool %s | grep \"Link detected\" > /tmp/eth.temp",interface);
- system(cmd);
- if (devflag==DEV_DOWN) {
- sprintf(cmd,"ifconfig %s down",interface);
- system(cmd);
- }
- fp=fopen("/tmp/eth.temp","r");
- if (fp==NULL) {
- system("rm -rf /tmp/eth.temp");
- return -1;
- }
- fgets(cmd,1024,fp);
- fclose(fp);
- system("rm -rf /tmp/eth.temp");
- tt=strstr(cmd,"no");
- if (tt!=NULL) return LINK_DOWN;
- tt=strstr(cmd,"yes");
- if (tt!=NULL) return LINK_UP;
- return -1;
- }
用c/c++实现linux下检测网络接口状态
- #include <sys types.h="">
- #include <string.h>
- #include <stdlib.h>
- #include <sys ioctl.h="">
- #include <stdio.h>
- #include <errno.h>
- #include <net if.h="">
- struct ethtool_value {
- __uint32_t cmd;
- __uint32_t data;
- };
- int main(int , char* [])
- {
- struct ethtool_value edata;
- int fd = -1, err = 0;
- struct ifreq ifr;
- memset(&ifr, 0, sizeof(ifr));
- strcpy(ifr.ifr_name, "eth0");
- fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd < 0) {
- perror("Cannot get control socket");
- return 70;
- }
- edata.cmd = 0x0000000a;
- ifr.ifr_data = (caddr_t)&edata;
- err = ioctl(fd, 0x8946, &ifr);
- if (err == 0) {
- fprintf(stdout, "Link detected: %s\n",
- edata.data ? "yes":"no");
- } else if (errno != EOPNOTSUPP) {
- perror("Cannot get link status");
- }
- return 0;
- }  
- #include <net if.h=""> // IFF_RUNNING
- //如果网卡已脸上网线,返回0,否则返回-1.
- int check_nic(char *nic)
- {
- struct ifreq ifr;
- int skfd = socket(AF_INET, SOCK_DGRAM, 0);
- strcpy(ifr.ifr_name, nic_name);
- if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0)
- {
- return -1;
- }
- if(ifr.ifr_flags & IFF_RUNNING)
- return 0; // 网卡已插上网线
- else return -1;
- }
 GitHub 加速计划 / li / linux-dash
 GitHub 加速计划 / li / linux-dash 10
10
             2
2
             下载
下载
            
          A beautiful web dashboard for Linux
        
 
          最近提交(Master分支:1 个月前 )
 186a802e 
added ecosystem file for PM2 5 年前 
5def40a3 
Add host customization support for the NodeJS version 5 年前 
 
 新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐



所有评论(0)