傳送arp請求報文
阿新 • • 發佈:2018-12-07
(1)報文格式
(2)程式碼如下:
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/ethernet.h> #include <netpacket/packet.h> #include <string.h> #include <net/if.h> #define SRC_MAC { 0x00,0x0C,0x29,0x6F,0x57,0xE7 }//源MAC地址 #define DEST_MAC { 0x00,0x0C,0x29,0xD3,0xD6,0xF7 }//目的MAC地址 struct arppacket { unsigned char dest_mac[ETH_ALEN];//接收方MAC unsigned char src_mac[ETH_ALEN];//傳送方MAC unsigned short type; //0x0806是ARP幀的型別值 unsigned short ar_hrd;//硬體型別 - 乙太網型別值0x1 unsigned short ar_pro;//上層協議型別 - IP協議(0x0800) unsigned char ar_hln;//MAC地址長度 unsigned char ar_pln;//IP地址長度 unsigned short ar_op;//操作碼 - 0x1表示ARP請求包,0x2表示應答包 unsigned char ar_sha[ETH_ALEN];//傳送方mac unsigned char ar_sip[4];//傳送方ip unsigned char ar_tha[ETH_ALEN];//接收方mac unsigned char ar_tip[4];//接收方ip } __attribute__ ((__packed__)); int main(int argc,char *argv[]) { int fd = 0; struct in_addr s,r; struct sockaddr_ll sl; struct arppacket arp={ DEST_MAC, SRC_MAC, htons(0x0806), htons(0x01), htons(0x0800), ETH_ALEN, 4, htons(0x01), SRC_MAC, {0}, DEST_MAC, {0} }; fd = socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL)); if(fd < 0) { printf("socket error\n"); return -1; } memset(&sl, 0, sizeof(sl)); inet_aton("192.168.11.220", &s); memcpy(&arp.ar_sip, &s, sizeof(s)); inet_aton("192.168.11.192", &r); memcpy(&arp.ar_tip, &r, sizeof(r)); sl.sll_family = AF_PACKET; sl.sll_ifindex = IFF_BROADCAST; while(1) { if(sendto(fd,&arp, sizeof(arp), 0, (struct sockaddr*)&sl, sizeof(sl)) <= 0) { printf("send error\n"); } else printf("send success\n"); sleep(1); } close(fd); return 0; }