部分转自http://www.cnblogs.com/zht-blog/p/4025903.html
int ioctl(int d, int request, ...);
ioctl用来控制特殊设备文件的属性,第一个参数fd必须是一个已经打开的文件描述符,
第三个参数一般为char *argp,它随第二个参数request的不同而不同,参数request决定了参数argp是向ioctl传递数据还是从ioctl获取数据。
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
unsigned char g_eth_name[16];
unsigned char g_macaddr[6];
unsigned int g_broadcast_addr;
int main()
{
int i;
int rv;
int fd;
struct ifreq ifr;
struct sockaddr_in sin;
char ipaddr[50];
fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == fd)
{
return;
}
strcpy(g_eth_name, "eth0");
strcpy(ifr.ifr_name, g_eth_name);
if ( ioctl(fd, SIOCGIFHWADDR, &ifr) < 0)
{
close( fd );
return;
}
memcpy(g_macaddr, ifr.ifr_hwaddr.sa_data, sizeof(g_macaddr));
printf("local mac:");
for(i=0;i<sizeof(g_macaddr)-1;i++)
{
printf("%.2x:", g_macaddr[i]);
}
printf("%.2x\n", g_macaddr[i]);
//get the broadcast addr
if ( ioctl(fd, SIOCGIFBRDADDR, &ifr) < 0)
{
close( fd );
return;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
g_broadcast_addr = sin.sin_addr.s_addr;
printf("broadcast is :%s\n", inet_ntoa(sin.sin_addr));
//set the mask
struct sockaddr_in *sin_net_mask;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name )-1);
sin_net_mask = (struct sockaddr_in *)&ifr.ifr_addr;
sin_net_mask->sin_family = AF_INET;
inet_pton(AF_INET, "255.255.255.0", &sin_net_mask ->sin_addr);
if (ioctl(fd, SIOCSIFNETMASK, &ifr ) < 0)
{
close( fd );
printf("set net mask error:%s\n", strerror(errno));
return;
}
close( fd );