检测网卡物理连接的方法
/* Check network adapter is up or down */
// Note: one or two adapter drivers may be not support this method
// exemple: based virtual machine
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/sockios.h>
#include <linux/types.h>
const char* VERSION = "0.6.0.48 --maintain by isnowran";
struct mii_data
{
__u16 phy_id;
__u16 reg_num;
__u16 val_in;
__u16 val_out;
};
int main( int argc, char* argv[] )
{
if( argc != 2 )
{
printf( "Version: %s\n", VERSION );
printf( "Useage: argv[0] ethNO.\n" );
return 0;
}
int skfd = 0;
if( ( skfd = socket( AF_INET, SOCK_DGRAM, 0 ) ) < 0 )
{
perror( "socket" );
return -1;
}
struct ifreq ifr;
bzero( &ifr, sizeof( ifr ) );
strncpy( ifr.ifr_name, argv[1], IFNAMSIZ - 1 );
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if( ioctl( skfd, SIOCGMIIPHY, &ifr ) < 0 )
{
perror( "ioctl" );
return -1;
}
struct mii_data* mii = NULL;
mii = (struct mii_data*)&ifr.ifr_data;
mii->reg_num = 0x01;
if( ioctl( skfd, SIOCGMIIREG, &ifr ) < 0 )
{
perror( "ioctl2" );
return -1;
}
if( mii->val_out & 0x0004 )
printf( "Linkup\n" );
else
printf( "Linkdown\n" );
close( skfd );
return 0;
}