Linux network advanced programming-analysis of data packets at each layer

We stole a picture online

We use raw sockets to verify the authenticity of this picture [I know it is true]

#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/ether.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <stdio.h>


static int32_t Debug = 1;

using namespace std;

int32_t main(int32_t argc, const char *argv[])
{
    unsigned char buf[1519]; // 1518 + 1
	int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	string line(50, '-');
	while(1) {// 解析协议  这些协议的字段我在网络篇都介绍了
        cout << line << endl;
		unsigned char src_mac[18] = "";
		unsigned char dst_mac[18] = "";
		recvfrom(sock_raw_fd, buf, sizeof(buf), 0, NULL, NULL);
		//"%x:%x:%x:%x:%x:%x"
		sprintf((char*)dst_mac, "%02x:%02x:%02x:%02x:%02x:%02x",  // MAC
			buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]);
	
		sprintf((char*)src_mac, "%02x:%02x:%02x:%02x:%02x:%02x",
			buf[6],buf[7],buf[8],buf[9],buf[10],buf[11]);
        
        printf(" MAC : src_mac: %s => dst_mac: %s\n", src_mac, dst_mac);
        if(buf[12] == 0x08 && buf[13] == 0x00){ // IP
            printf("IP packet \n");
            unsigned char src_ip[17] = "";
		    unsigned char dst_ip[17] = "";
            sprintf((char*)src_ip, "%d.%d.%d.%d", buf[26],buf[27],buf[28],buf[29]);
            sprintf((char*)dst_ip, "%d.%d.%d.%d", buf[30],buf[31],buf[32],buf[33]);

             printf(" IP : src_ip: %s => dst_ip: %s\n", src_ip, dst_ip);
            if(buf[23] == 6){
                printf("TCP packet\n");
            }else if(buf[23] == 17){
                printf("UDP packet\n");
            }
            
        }else if(buf[12] == 0x08 && buf[13] == 0x06){
            printf("ARP packet\n");
        }else if(buf[12] == 0x80 && buf[13] == 0x35){
            printf("RARP packet\n");
        }
	    cout << line << endl;
        memset(buf, 0, sizeof(buf));
	}


	return 0;
}

Effect: [ Execute program must add sudo (execute with root authority) ]

Here should be the interaction information between my remote terminal shell and the virtual machine

Ubuntu information in the virtual machine

Local host information

Verified successfully 

 

Guess you like

Origin blog.csdn.net/qq_44065088/article/details/109272062