网络第二课(2)-arp请求

来源:互联网 发布:档案数字化软件著作权 编辑:程序博客网 时间:2024/05/14 02:59

关于arp包(地址解析协议)微笑

arp请求与arp应答;然后通过tcpdump来捕捉我们的arp请求与arp应答。

arp请求(知道对方的ip地址,要得到对方的mac地址):我们通过我们pc的网卡,来向我们的局域网内的所有用户,发送一个广播(当我们的arp请求发出的时候,tcpdump就能捕捉到,从我们网卡发出的arp请求);

arp应答:如果对方是我们请求的ip,这一个用户就应答我们(发送一个单播,把自己的mac地址填到,我们之前发送过去的数据,然后发给我们。);如果不是我们请求的ip,这个用户就丢掉,我们的arp请求。

arp心跳:就是我们os每隔一个心跳,就向我们局域网内发送一个arp广播,这样我们就可以知道局域网内联上网的用户,把这些用户的ip/mac放到我们的arp缓存里面。当我们要通信的时候,就不用直接发送arp请求来,来获得我们要通信对方的ip/mac。如上网页:http:直接http请求与http应答。

#include <stdio.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <linux/socket.h>
#include <string.h>
#pragma pack(1)
struct machdr{
    
    unsigned char dest[6];    
    unsigned char source[6];
    unsigned short proto;
};
struct arphdr{
    unsigned short hd;
    unsigned short proto;
    unsigned char  hd_len;
    unsigned char  proto_len;
    unsigned short option;    
    unsigned char source_eth[6];    
    unsigned long source_ip;
    unsigned char dest_eth[6];    
    unsigned long dest_ip;
};
int main()
{
    printf("%d",sizeof(struct machdr)+sizeof(struct arphdr));
    
    int ret= 0;
    int fd = socket(AF_INET,SOCK_PACKET,htons(ETH_P_RARP));
    if(fd < 0)
    {
        perror("socket");    
        return 1;
    }
    unsigned char buff[1024] = {0};
    //mac
    struct machdr *mac = (struct machdr *)buff;
    mac->dest[0] =0xff;//对方的mac全充1;发送arp请求后,对方os为填充自已的mac,然后做出应答。
    mac->dest[1] = 0xff;    
    mac->dest[2] = 0xff;    
    mac->dest[3]= 0xff;    
    mac->dest[4]= 0xff;    
    mac->dest[5]=0xff;    

    mac->source[0]= 0x6c;//源mac   
    mac->source[1]= 0xf0;    
    mac->source[2]= 0x49;    
    mac->source[3]= 0x89;    
    mac->source[4]= 0xd2;    
    mac->source[5]= 0x54;    
                
    mac->proto = htons(0x0806);//表明上层为arp

    //arp
    struct arphdr *arp = (struct arphdr *)(buff+14);
                
    arp->hd = htons(1);
    arp->proto = htons(0x0800);
    arp->hd_len = 6;    
    arp->proto_len = 4;
    arp->option = htons(1);
    arp->dest_eth[0] =0xff;
    arp->dest_eth[1] = 0xff;    
    arp->dest_eth[2] = 0xff;    
    arp->dest_eth[3]= 0xff;    
    arp->dest_eth[4]= 0xff;    
    arp->dest_eth[5]=0xff;    
    arp->dest_ip = inet_addr("192.168.50.148");//这是对方的ip
    // 6C:F0:49:89:D2:54
    arp->source_eth[0]= 0x6c;    
    arp->source_eth[1]= 0xf0;    
    arp->source_eth[2]= 0x49;    
    arp->source_eth[3]= 0x89;    
    arp->source_eth[4]= 0xd2;    
    arp->source_eth[5]= 0x54;    
                
    arp->source_ip = inet_addr("192.168.50.142");//这是我的ip

    struct sockaddr a;
    a.sa_family = AF_INET;
    strcpy(a.sa_data,"eth0");

   ret = sendto(fd,buff,42,0,&a,sizeof(str uct sockaddr));//send是面向连接的;sendto是面向无连接的
    if(ret < 0)
    {
        perror("sendto");
        return 1;
    }    
    
    return 0;
}
   
原创粉丝点击