关闭

linux中读取网卡插拔状态

标签: linuxstructsocketnetworkfunctionup
1426人阅读 评论(1) 收藏 举报
分类:

原创文章,转载请说明出处:

http://blog.csdn.net/alleincao/article/details/7414462

废话不多说,直接上程序:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/ethtool.h>
#include <linux/sockios.h>

typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned char u8;

int detect_mii(int skfd, char *ifname)
{
   struct ifreq ifr;
   u16 *data, mii_val;
   unsigned phy_id;

   /* Get the vitals from the interface. */
   strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

   if (ioctl(skfd, SIOCGMIIPHY, &ifr) < 0)
      {
         fprintf(stderr, "SIOCGMIIPHY on %s failed: %s/n", ifname, strerror(errno));
         (void) close(skfd);
         return 2;
      }

   data = (u16 *)(&ifr.ifr_data);
   phy_id = data[0];
   data[1] = 1;

   if (ioctl(skfd, SIOCGMIIREG, &ifr) < 0)
     {
        fprintf(stderr, "SIOCGMIIREG on %s failed: %s/n", ifr.ifr_name, strerror(errno));
        return 2;
     }

   mii_val = data[3];
   return(((mii_val & 0x0016) == 0x0004) ? 0 : 1);
}

int detect_ethtool(int skfd, char *ifname)
{
   struct ifreq ifr;
   struct ethtool_value edata;
   memset(&ifr, 0, sizeof(ifr));
   edata.cmd = ETHTOOL_GLINK;

   strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)-1);
   ifr.ifr_data = (char *) &edata;

   if (ioctl(skfd, SIOCETHTOOL, &ifr) == -1)
     {
        printf("ETHTOOL_GLINK failed: %s/n", strerror(errno));
        return 2;
     }

   return (edata.data ? 0 : 1);
}

/*================================================================================

FUNCTION: CheckNet

DESCRIPTION:
   check network status

ARGUMENTS PASSED:
   None.

RETURN VALUE:
   0 up
   1 down
   2 error
==================================================================================*/
int CheckNet()
{
	int skfd = -1;
	char *ifname = "eth0";
	int retval;

	/* Open a socket. */
	if (( skfd = socket( AF_INET, SOCK_DGRAM, 0 ) ) < 0 )
	{
		printf("socket error/n");
		exit(-1);
	}

	retval = detect_ethtool(skfd, ifname);
	if (retval == 2)
	retval = detect_mii(skfd, ifname);

	close(skfd);

	return retval;
}

int main(int argc, char **argv)
{
	int ret = -1,retold = -1;
	while(1)
	{
		ret = CheckNet();
		if(ret != retold)
		{
			retold = ret;
			if (ret == 2)
				printf("Could not determine status/n");
			if (ret == 1)
				printf("Link down\n");
			if (ret == 0)
				printf("Link up\n");
		}
	}
}






   
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21450次
    • 积分:296
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:3篇
    • 译文:0篇
    • 评论:2条
    最新评论