linux之ioctl函数解析
[lingyun@localhost ioctl_1]$ ls
ipconfig.c
[lingyun@localhost ioctl_1]$ cat ipconfig.c
/*********************************************************************************
* Copyright: (C) 2013 fulinux<fulinux@sina.com>
* All rights reserved.
*
* Filename: ioctl.c
* Description: This file
*
* Version: 1.0.0(08/01/2013~)
* Author: fulinux <fulinux@sina.com>
* ChangeLog: 1, Release initial version on "08/01/2013 03:21:50 PM"
*
********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
static void usage()
{
printf("usage: ipconfig interface\n");
exit(0);
}
int main(int argc, char **argv)
{
struct sockaddr_in *addr;
struct ifreq ifr;
char *name,*address;
int sockfd;
if(argc != 2)
usage();
else
name = argv[1];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
if(ioctl(sockfd, SIOCGIFADDR,&ifr) == -1)
perror("ioctl error"), exit(1);
addr = (struct sockaddr_in *)&(ifr.ifr_addr);
address = inet_ntoa(addr->sin_addr);
printf("inet addr: %s\n", address);
if(ioctl(sockfd, SIOCGIFBRDADDR, &ifr) == -1)
perror("ioctl error"),exit(1);
addr = (struct sockaddr_in *)&ifr.ifr_broadaddr;
address = inet_ntoa(addr->sin_addr);
printf("broad addr: %s\n", address);
if(ioctl(sockfd, SIOCGIFNETMASK, &ifr) == -1)
perror("ioctl error"), exit(1);
addr = (struct sockaddr_in *)&ifr.ifr_addr;
address = inet_ntoa(addr->sin_addr);
printf("inet mask: %s\n", address);
printf(" ");
exit(0);
}
[lingyun@localhost ioctl_1]$ gcc -o ipconfig ipconfig.c
[lingyun@localhost ioctl_1]$ ./ipconfig eth0
inet addr: 192.168.1.3
broad addr: 192.168.1.255
inet mask: 255.255.255.0
[lingyun@localhost ioctl_1]$