C language realizes the method of linux network card connection detection

  • 2020-06-03 08:02:45
  • OfStack

This paper shares the specific code of C language to realize linux network card connection detection for your reference. The specific content is as follows

I'm just going to code it


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
 
 
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <linux/mii.h>
#include <linux/sockios.h>
#include <errno.h>
 
 
int get_if_miireg(const char *if_name, int phy_id, int reg_num )
{
 int fd = -1; 
 struct ifreq ifr; 
 struct mii_ioctl_data *mii; 
 int value; 
 
 if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
 {
 perror("socket");
 close(fd);
 return -1; 
 }
 
 bzero(&ifr, sizeof(ifr));
 strncpy(ifr.ifr_name, if_name, IFNAMSIZ-1); 
 ifr.ifr_name[IFNAMSIZ-1] = 0; 
 
 if (ioctl(fd, SIOCGMIIPHY, &ifr) < 0)
 { 
 perror("ioctl");
 close(fd);
 return -1; 
 }
 
 mii = (struct mii_ioctl_data *)&ifr.ifr_data;
 mii->reg_num = reg_num;//0x01
 if (ioctl(fd, SIOCGMIIREG, &ifr) < 0)
 { 
 perror("ioctl");
 close(fd);
 return -1;
 }
 close(fd);
 value = ((mii->val_out&0x04)>>2);
 return value;
}
 
int main(int argc, char* argv[])
{
  int i=0;
  if(argc != 2)
  {
    fprintf(stderr, "usage: %s <ethname>", argv[0]);
    return -1;
  }
 
  i = get_if_miireg(argv[1],0x10,0x01);
  printf( "if_status = %d\n", i );
  return 0;
}

It can only identify whether the network cable is connected or not. It has not identified whether the network card exists or whether it is down.


Related articles: