通过使用ioctl可以获得本机的一些信息,这里记录获得interface IP及MAC的过程。
1:ioctl 函数的作用是什么
man ioctl:
DESCRIPTION
The ioctl() function manipulates the underlying device parameters of special files. In particular, many operating characterisâ€
tics of character special files (e.g., terminals) may be controlled with ioctl() requests. The argument fd must be an open file
descriptor.
The second argument is a device-dependent request code. The third argument is an untyped pointer to memory. It's traditionally
char *argp (from the days before void * was valid C), and will be so named for this discussion.
An ioctl() request has encoded in it whether the argument is an in parameter or out parameter, and the size of the argument argp
in bytes. Macros and defines used in specifying an ioctl() request are located in the file <sys/ioctl.h>.
2:测试例子
/*
用socket获得当前interface的信息
1:ip地址
2:mac地址
3:interface index
注:创建的是原始套接字,编译及执行都需要root权限
*/
int read_interface(const char* interface)
{
int fd;
int ret = ;
struct ifreq ifr;
struct sockaddr_in *ip_addr = NULL;
char mac[] = {};
memset(&ifr, , sizeof(struct ifreq));
fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (fd > ){
ifr.ifr_addr.sa_family = AF_INET;
strcpy(ifr.ifr_name, interface); //get interface ip
if(ioctl(fd, SIOCGIFADDR, &ifr) == ){
ip_addr = (struct sockaddr_in *)&ifr.ifr_addr;
printf("The %s ip addr is %s\n",ifr.ifr_name,inet_ntoa(ip_addr->sin_addr));
} else {
printf("SIOCGIFADDR failed, error:%s\n", strerror(errno));
ret = -;
goto out;
} //get interface mac
if(ioctl(fd, SIOCGIFHWADDR, &ifr) == ){
memcpy(mac, ifr.ifr_hwaddr.sa_data, );
printf("interface mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
mac[],mac[],mac[],mac[],mac[],mac[]);
} else {
printf("SIOCGIFHWADDR failed, error:%s\n", strerror(errno));
ret = -;
goto out;
} //get interface index
if (ioctl(fd, SIOCGIFINDEX, &ifr) == ) {
printf("The interface index:%d\n",ifr.ifr_ifindex);
} else {
printf("SIOCGIFINDEX failed, error:%s\n", strerror(errno));
ret = -;
goto out;
}
} else {
printf("%s\n",strerror(errno));
ret = -;
}
out:
close(fd);
return ret;
}
3:ioctl的第二个参数有很多,了解它们可以在需要时使用
参考:http://blog.csdn.net/evenness/article/details/7665970