Linux下获取IP和MAC Adr的方法



Linux下获取IP和MAC Adr的方法
 
struct   ifreq   {
 
        char         ifr_name[IFNAMSIZ];    
        union   {
                struct     sockaddr   ifru_addr;
                struct     sockaddr   ifru_dstaddr;
                struct     sockaddr   ifru_broadaddr;
                short      ifru_flags;
                int        ifru_metric;
                caddr_t    ifru_data;
        }   ifr_ifru;
}; 
  www.2cto.com  
#include   <net/if.h>
#include   <net/if_arp.h>
 
#include   <arpa/inet.h>
#include   <errno.h>
 
#define   ETH_NAME   "eth0"
 
int   main()
  {
       int   sock;
       struct   sockaddr_in   sin;
       struct   ifreq   ifr;
       unsigned char arp[6] ;  www.2cto.com  
 
       sock   =   socket(AF_INET,   SOCK_DGRAM,   0);
       if   (sock   ==   -1)
       {
            perror("socket");
            return   -1;
        }
 
        strncpy(ifr.ifr_name,   ETH_NAME,   IFNAMSIZ);
         ifr.ifr_name[IFNAMSIZ   -   1]   =   0;
 
        if   (ioctl(sock,   SIOCGIFADDR,   &ifr)   ==  0)  //获取ip
        {
 
            memcpy(&sin,   &ifr.ifr_addr,   sizeof(sin));
 
            fprintf(stdout,   "eth0:   %s\n",   inet_ntoa(sin.sin_addr));
         }  www.2cto.com  
 
 
         if( ioctl( sock, SIOCGIFHWADDR, &ifr ) == 0 )   //获取mac
 
         {
 
             memcpy( arp, ifr.ifr_hwaddr.sa_data, 6 );
             printf( "adapter hardware address x:x:x:x:x:x\n", 
                                   arp[0], arp[1], arp[2], arp[3], arp[4], arp[5] );
 
          }
                 
         return   0;
  }
 

相关内容

    暂无相关文章