2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <net/if_arp.h>
7 #include <string.h>
8 #include <linux/sockios.h>
9 int main(int argc,char *argv[])
10 {
11 int s;
12 struct arpreq arpreq;
13 struct sockaddr_in *addr=(struct sockaddr_in*)&arpreq.arp_pa;
14 unsigned char *hw;
15 int err=-1;
16 if(argc<2)
17 {
18 printf("错误的使用方式,格式为:\n myarp ip(myarp 127.0.0.1)\n");
19 return -1;
20 }
21 s=socket(AF_INET,SOCK_DGRAM,0);
22 if(s<0)
23 {
24 printf("socket()出错\n");
25 return -1;
26 }
27 //填充arpreq的成员arp_pa
28 addr->sin_family=AF_INET;
29 addr->sin_addr.s_addr=inet_addr(argv[1]);
30 if(addr->sin_addr.s_addr==INADDR_NONE)
31 {
32 printf("IP地址格式错误\n");
33 }
34 //网络接口为eth0
35 strcpy(arpreq.arp_dev,"eth0");
36 err=ioctl(s,SIOCGARP,&arpreq);
37 if(err<0)
38 {
39 printf("IOCTL错误\n");
40 return -1;
41 }
42 else
43 {
44 hw=(unsigned char*)&arpreq.arp_ha.sa_data; //硬件地址
45 printf("%s:",argv[1]);
46 printf("%02x:%02x:%02x:%02x:%02x:%02x",hw[0],hw[1],hw[2],hw[3],hw[4],hw[5]);
47 }
48 close(s);
49 return 0;
50 }