转自:http://bbs.chinaunix.net/thread-1940813-2-1.html
//copy by duanjigang from source code of ethtool 6
struct ethtool_cmd
{
__u32 cmd;
__u32 supported; /* Features this interface supports */
__u32 advertising; /* Features this interface advertises */
__u16 speed; /* The forced speed, 10Mb, 100Mb, gigabit */
__u8 duplex; /* Duplex, half or full */
__u8 port; /* Which connector port */
__u8 phy_address;
__u8 transceiver; /* Which transceiver to use */
__u8 autoneg; /* Enable or disable autonegotiation */
__u32 maxtxpkt; /* Tx pkts before generating tx int */
__u32 maxrxpkt; /* Rx pkts before generating rx int */
__u32 reserved[4];
};
int get_settings(const char* devname)
{
struct ifreq ifr;
int fd;
struct ethtool_cmd ecmd;
int allfail = 1;
/* Setup our control structures. */
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, devname);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
return -1;
}
ecmd.cmd = 1;
ifr.ifr_data = (caddr_t)&ecmd;
if(ioctl(fd, SIOCETHTOOL, &ifr))
{
close(fd);
return -1;
}
//duplex 0 half 1 full
fprintf(stdout, "Settings for %s: speed:%d, duplex:%s\n", devname, ecmd.speed, ecmd.duplex ? "full" : "half");
close(fd);
return 1;
}
http://hi.baidu.com/deep_pro/blog/item/8473bed9df3bce2010df9bfc.html
#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>
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned char u8;
#include <linux/ethtool.h>
#include <linux/sockios.h>
int get_settings(const char* devname)
{
struct ifreq ifr;
int fd;
struct ethtool_cmd ecmd;
int allfail = 1;
/* Setup our control structures. */
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, devname);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0)
{
return -1;
}
ecmd.cmd = 1;
ifr.ifr_data = (caddr_t)&ecmd;
if(ioctl(fd, SIOCETHTOOL, &ifr))
{
close(fd);
perror("SIOCETHTOOL");
return -1;
}
//duplex 0 half 1 full
fprintf(stdout, "Settings for %s: speed:%d, duplex:%s\n", devname, ecmd.speed,
ecmd.duplex ? "full" : "half");
close(fd);
return 1;
}
int main(int argc, char *argv[])
{
int ret =get_settings(argv[1]);
printf("%d\n",ret);
return EXIT_SUCCESS;
}