精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>C/C++>>网络与通讯>>get ip/mac (full source code)

主题:get ip/mac (full source code)
发信人: xgh()
整理人: wenbobo(2002-12-27 15:54:18), 站内信件
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/ioctl.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <net/if.h>
#include <net/if_arp.h>

#define ETH_ALEN 14

int
main(int argc, char **argv)
{
        char            *pptr, nowaddr[8];
        unsigned char   ptr[ETH_ALEN];
        struct hostent  *hptr;
        struct sockaddr_in sin, nowsin;
        struct ifreq  nowif;
        int    nowsock;
        struct utsname  nownode;
        struct sockaddr nowsckaddr;

        uname(&nownode);
        hptr = gethostbyname(nownode.nodename);

        bzero(&sin, sizeof(sin));
        sin.sin_family = hptr->h_addrtype;
        memcpy(&sin.sin_addr, hptr->h_addr, hptr->h_length);
        pptr = inet_ntoa(sin.sin_addr);
        printf("%s\n", pptr);

        nowsock = socket(AF_INET, SOCK_DGRAM, 0);
//      memcpy(&nowif.arp_pa, &sin.sin_addr, sizeof(sin.sin_addr));
        bcopy("eth1", nowif.ifr_name, IFNAMSIZ);
        printf("the interface is %s\n", nowif.ifr_name);
        if(ioctl(nowsock, SIOCGIFHWADDR, &nowif) < 0) {
printf("ioctl error!!\n");
exit (-1);
}
nowsckaddr = (struct sockaddr)nowif.ifr_hwaddr;
bcopy(&nowsckaddr.sa_data, ptr, ETH_ALEN);

printf("%d,%d,%d,%d,%d,%d\n", *ptr, *(ptr+1), *(ptr+2), *(ptr+3),
*(ptr+4), *(ptr+5));
printf("%02X:%02X:%02X:%02X:%02X:%02X\n", *ptr, *(ptr+1), *(ptr+2), *(ptr+3),
*(ptr+4), *(ptr+5));
sprintf(nowaddr, "%02X", *(ptr+2));
sprintf(nowaddr+2, "%02X", *(ptr+3));
sprintf(nowaddr+4, "%02X", *(ptr+4));
sprintf(nowaddr+6, "%02X", *(ptr+5));
printf("%s\n", nowaddr);
close(nowsock);

}

--
※ 来源:.网易 BBS bbs.netease.com.[FROM: bbs.szptt.net.cn]

[关闭][返回]