1、结构定义
struct ifreq
{
#define IFHWADDRLEN 6
union
{
char ifrn_name[IFNAMSIZ];
} ifr_ifrn;
union
{
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct ifmap ifru_map;
char ifru_slave[IFNAMSIZ];
char ifru_newname[IFNAMSIZ];
void __user * ifru_data;
struct if_settings ifru_settings;
} ifr_ifru;
};
#define ifr_name ifr_ifrn.ifrn_name
#define ifr_hwaddr ifr_ifru.ifru_hwaddr
#define ifr_addr ifr_ifru.ifru_addr
#define ifr_dstaddr ifr_ifru.ifru_dstaddr
#define ifr_broadaddr ifr_ifru.ifru_broadaddr
#define ifr_netmask ifr_ifru.ifru_netmask
#define ifr_flags ifr_ifru.ifru_flags
#define ifr_metric ifr_ifru.ifru_ivalue
#define ifr_mtu ifr_ifru.ifru_mtu
#define ifr_map ifr_ifru.ifru_map
#define ifr_slave ifr_ifru.ifru_slave
#define ifr_data ifr_ifru.ifru_data
#define ifr_ifindex ifr_ifru.ifru_ivalue
#define ifr_bandwidth ifr_ifru.ifru_ivalue
#define ifr_qlen ifr_ifru.ifru_ivalue
#define ifr_newname ifr_ifru.ifru_newname
#define ifr_settings ifr_ifru.ifru_settings
struct ifconf
{
int ifc_len; /* size of buffer */
union
{
char *ifcu_buf; /* input from user->kernel*/
struct ifreq *ifcu_req; /* return from kernel->user*/
} ifc_ifcu;
};
2、用法说明
ifreq结构定义在/usr/include/net/if.h,用来配置ip地址,激活接口,配置MTU等接口信息的。其中包含了一个接口的名字和具体内容——(是个共用体,有可能是IP地址,广播地址,子网掩码,MAC号,MTU或其他内容)。ifreq包含在ifconf结构中。而 ifconf结构通常是用来保存所有接口的信息的。
3、获取网络信息
static int get_net_info(const char *eth_name, uint32_t *ipaddr, uint32_t *netmask, uint32_t *gateway, uint32_t *bcast_addr)
{
int skfd = -1;
struct ifreq ifr;
skfd = socket(PF_INET, SOCK_DGRAM, 0);
if (skfd < 0)
{
return -1;
}
if(eth_name == NULL)
{
strcpy(ifr.ifr_name, "eth0");
}
else
{
strcpy(ifr.ifr_name, eth_name);
}
if (ioctl(skfd, SIOCGIFADDR, &ifr) == 0)
{
*ipaddr = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr.s_addr;
}
if (ioctl(skfd, SIOCGIFNETMASK, &ifr) == 0)
{
*netmask = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr.s_addr;
}
if (ioctl(skfd, SIOCGIFBRDADDR, &ifr) == 0)
{
*bcast_addr = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr.s_addr;
}
close(skfd);
if (eth_name == NULL)
{
get_gateway(gateway);
}
else
{
if(strcmp(eth_name, ETH0) == 0)
{
*gateway = inet_addr(sysconfig_get_value("net", "gateway"));
}
else
{
*gateway = inet_addr(sysconfig_get_value("net", "gateway2"));
}
}
return 0;
}