欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

C语言+shell实现linux网卡状态检测

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

本文实例为大家分享了C语言+shell实现linux网卡状态检测的具体代码,供大家参考,具体内容如下

不解释,直接上代码 要求linux环境具备grep和awk(awk可选)

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
int get_if_status(char *if_name)
{
  char  buffer[BUFSIZ];
 char  cmd[100];
  FILE  *read_fp;
  int    chars_read;
  int    ret =0;
  
  memset( buffer, 0, BUFSIZ );
  memset( cmd, 0, 100 );
 sprintf(cmd, "ifconfig -a | grep %s",if_name);
  read_fp = popen(cmd, "r");
  if ( read_fp != NULL )
  {
    chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
 pclose(read_fp);
 
    if (chars_read > 0)
    {
      ret = 1;
    }
    else
    {
  fprintf(stderr, "%s: NO FOUND\r\n",if_name);
  return 0;
    }
  }
 
 if(ret == 1)
 {
 memset( buffer, 0, BUFSIZ );
 memset( cmd, 0, 100 );
 sprintf(cmd, "ifconfig |grep %s",if_name);
 read_fp = popen(cmd, "r");
 if ( read_fp != NULL )
 {
   chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
   pclose(read_fp);
  
   if (chars_read > 0)
   {
     ret = 2;
   }
   else
   {
  fprintf(stderr, "%s: DOWN\r\n",if_name);
  return 1;
   }
 }
 }
 
 if(ret == 2)
 {
 memset( buffer, 0, BUFSIZ );
 memset( cmd, 0, 100 );
 sprintf(cmd, "ifconfig %s | grep RUNNING | awk '{print $3}'",if_name);
 read_fp = popen(cmd, "r");
 if ( read_fp != NULL )
 {
   chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp);
   pclose(read_fp);
  
   if (chars_read > 0)
   {
  fprintf(stderr, "%s: LINKED\r\n",if_name);
  return 3;
   }
   else
   {
  fprintf(stderr, "%s: UNPLUGGED\r\n",if_name);
  return 2;
   }
 }
 }
 
 return -1;
}
 
 
int main(int argc, char* argv[])
{
  int i=0;
 if(argc != 2)
 {
 fprintf(stderr, "usage: %s <ethname>", argv[0]);
 return -1;
 }
 
  i = get_if_status(argv[1]);
  printf( "if_status = %d\n", i );
  return 0;
}

嵌入式编译 mips-linux-gnu-gcc -mips32 -EL -mhard-float -Wall -o netlink netlink.c

测试结果

# ./netlink eth100
eth100: NO FOUND
if_status = 0
# 
# ifconfig eth0 down
# ./netlink eth0 
eth0: DOWN
if_status = 1
# 
# ifconfig eth0 up
# ./netlink eth0
eth0: UNPLUGGED
if_status = 2
#
# ./netlink eth0
eth0: LINKED
if_status = 3

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

上一篇:C++ 读文件 将文件内容读入到字符串string中的方法

栏    目:C语言

下一篇:C语言实现抢红包程序代码精简版

本文标题:C语言+shell实现linux网卡状态检测

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/737.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有