码迷,mamicode.com
首页 > 其他好文 > 详细

ioctl使用

时间:2014-05-20 18:46:37      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:linux c ioctl

#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];
           }
           strncpy(ifr.ifr_name, name, IFNAMSIZ-1);

           sockfd = socket(AF_INET, SOCK_DGRAM, 0);
           if(sockfd < 0)
           {
                   perror("socket() error!");
                   exit(1);
           }

           if(ioctl(sockfd, SIOCGIFHWADDR, &ifr)<0)
           {
                    perror("ioctl error");
                    exit(1);
           }
           printf("HWaddr: %02X:%02X:%02X:%02X:%02X:%02X\n", 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[0], 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[1], 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[2], 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[3], 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[4], 
                                        (unsigned char)ifr.ifr_hwaddr.sa_data[5]);

           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 ",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 ",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 ",address);

            printf("\n");
            close(sockfd);
            exit(0);
}


本文出自 “Howard” 博客,请务必保留此出处http://howard0217.blog.51cto.com/6646854/1413896

ioctl使用,布布扣,bubuko.com

ioctl使用

标签:linux c ioctl

原文地址:http://howard0217.blog.51cto.com/6646854/1413896

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!