1。通過已經連接配接的socket檔案擷取:
int getpeermac( int sockfd, char *buf )
{
int ret =0;
struct arpreq arpreq;
struct sockaddr_in dstadd_in;
socklen_t len = sizeof( struct sockaddr_in );
memset( &arpreq, 0, sizeof( struct arpreq ));
memset( &dstadd_in, 0, sizeof( struct sockaddr_in ));
if( getpeername( sockfd, (struct sockaddr*)&dstadd_in, &len ) < 0 )
err_err("getpeername()");
else
{
memcpy( &arpreq.arp_pa, &dstadd_in, sizeof( struct sockaddr_in ));
strcpy(arpreq.arp_dev, "eth1");
arpreq.arp_pa.sa_family = AF_INET;
arpreq.arp_ha.sa_family = AF_UNSPEC;
if( ioctl( sockfd, SIOCGARP, &arpreq ) < 0 )
err_err("ioctl SIOCGARP");
else
{
unsigned char* ptr = (unsigned char *)arpreq.arp_ha.sa_data;
ret = sprintf(buf, "%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5));
}
}
return ret;
}
2。 通過IP擷取:
int getpeermac_by_ip(char *ipaddr, char* buf)
int sockfd;
unsigned char *ptr;
struct sockaddr_in *sin;
struct sockaddr_storage ss;
char addr[INET_ADDRSTRLEN+1];
memset(addr, 0, INET_ADDRSTRLEN+1);
memset(&ss, 0, sizeof(ss));
if (argc != 2) {
printf("USAGE arpg ip_addr/n");
return -1;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("socket error");
sin = (struct sockaddr_in *) &ss;
sin->sin_family = AF_INET;
if (inet_pton(AF_INET, argv[1], &(sin->sin_addr)) <= 0) {
perror("inet_pton error");
sin = (struct sockaddr_in *) &arpreq.arp_pa;
memcpy(sin, &ss, sizeof(struct sockaddr_in));
strcpy(arpreq.arp_dev, "eth1");
arpreq.arp_ha.sa_family = AF_UNSPEC;
if (ioctl(sockfd, SIOCGARP, &arpreq) < 0) {
perror("ioctl SIOCGARP: ");
ptr = (unsigned char *)arpreq.arp_ha.sa_data;
sprintf(buf,"%x:%x:%x:%x:%x:%x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5));
return 0;
}