很久以前写的一个arp reply程序,关键时刻有时能派上用场,保存一下。有次自己服务器的IP不知道被哪个组的抢了,导致上不了网,而网管又找不到是哪台
服务器。实在没有办法,只用用此程序夺回了自己的IP。
注意这里IP地址和MAC地址都是假的。
#include <stdio.h>
#include <stdlib.h>
#include <net/ethernet.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SRC_IP "238.221.236.83"
#define TARGET_IP "238.221.236.119"
short SRC_MAC[]={0x00,0x03,0x1A,0x01,0x00,0x00};
short TARGET_MAC[]={0x00,0x12,0x25,0x9D,0xC1,0xF0};
void send_arp_reply(void);
int main(int argc ,char *args[])
{
while(1)
{
send_arp_reply();
sleep(30);
}
return 0;
}
void send_arp_reply(void)
{
struct ether_header *eth_hdr;
struct ether_arp *arp;
char datagram[60];
eth_hdr=(struct ether_header *)datagram;
memset(datagram,0,sizeof(datagram));
//set the ethernet header
eth_hdr->ether_dhost[0]=TARGET_MAC[0];
eth_hdr->ether_dhost[1]=TARGET_MAC[1];
eth_hdr->ether_dhost[2]=TARGET_MAC[2];
eth_hdr->ether_dhost[3]=TARGET_MAC[3];
eth_hdr->ether_dhost[4]=TARGET_MAC[4];
eth_hdr->ether_dhost[5]=TARGET_MAC[5];
eth_hdr->ether_shost[0]=SRC_MAC[0];
eth_hdr->ether_shost[1]=SRC_MAC[1];
eth_hdr->ether_shost[2]=SRC_MAC[2];
eth_hdr->ether_shost[3]=SRC_MAC[3];
eth_hdr->ether_shost[4]=SRC_MAC[4];
eth_hdr->ether_shost[5]=SRC_MAC[5];
eth_hdr->ether_type=htons(ETHERTYPE_ARP);
//set the arp header
arp=(struct arp*)(datagram+sizeof(struct ether_header));
arp->arp_hrd=htons(ARPHRD_ETHER);
arp->arp_pro=htons(ETHERTYPE_IP);
arp->arp_hln=6;
arp->arp_pln=4;
arp->arp_op=htons(2);
//arp body
//sender MAC and IP
memcpy((void*)arp->arp_sha,(void*)eth_hdr->ether_shost,6);
struct in_addr inadd_sender;
inet_aton(SRC_IP,&inadd_sender);
memcpy((void*)arp->arp_spa,(void*)&inadd_sender,4);
//target MAC and IP
memcpy((void*)arp->arp_tha,(void*)eth_hdr->ether_dhost,6);
struct in_addr inadd_target;
inet_aton(TARGET_IP,&inadd_target);
memcpy((void *)arp->arp_tpa,(void*)&inadd_target,4);
//establish socket
int fd=socket(AF_INET,SOCK_PACKET,htons(ETH_P_ARP));
if(fd<0)
{
perror("socket");
exit(-1);
}
struct sockaddr sa;
strcpy(sa.sa_data,"eth0");
sendto(fd,datagram,sizeof(datagram),0,&sa,sizeof(sa));
close(fd);
return ;
}