Skip to content

Instantly share code, notes, and snippets.

@rongyi
Created July 26, 2013 06:53
Show Gist options
  • Save rongyi/6086825 to your computer and use it in GitHub Desktop.
Save rongyi/6086825 to your computer and use it in GitHub Desktop.
check network interface status
#include <stdio.h>
#include <stdlib.h>
#include <linux/sockios.h>
#include <linux/ethtool.h>
#include <stdint.h>
#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <unistd.h>
#include <errno.h>
static int get_iface_status(const char *iface_name)
{
int sockfd;
struct ifreq ifr;
struct ethtool_value eval;
eval.cmd = ETHTOOL_GLINK;
/* eval.data = 0; */
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface_name, sizeof(ifr.ifr_name));
ifr.ifr_data = (char *)&eval;
if ((sockfd = socket(PF_PACKET, SOCK_DGRAM, 0)) == 0)
return -1;
if (ioctl(sockfd, SIOCETHTOOL, &ifr) == -1) {
close(sockfd);
perror("ioctrl");
return -1;
}
close(sockfd);
return eval.data;
}
int main()
{
const char *test_face = "eth0";
int ret = get_iface_status(test_face);
if (ret == 1)
printf("%s is up\n", test_face);
else
printf("%s is down\n", test_face);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment