Raw Socket Linux send/receive a packet

后端 未结 2 686
谎友^
谎友^ 2020-12-30 11:51

Have some problems in receiving packets. I can receive and read incoming packets, but I think i do not get a handshake with any host. I only want to send a packet to a remot

相关标签:
2条回答
  • 2020-12-30 12:04
    ip = (struct iphdr*) buffer;
    tcp = (struct tcphdr*) (buffer + sizeof(struct tcphdr)); //This is wrong
    

    Here to get array index of tcp header in buffer, you need to add sizeof(struct iphdr) to buffer like mentioned below.

    ip = (struct iphdr*) buffer;
    tcp = (struct tcphdr*) (buffer + sizeof(struct iphdr)); //This is correct
    
    0 讨论(0)
  • 2020-12-30 12:27
    1. You're receiving and storing packets in buffer, but you're printing data from ip and tcp without parsing that buffer. You should parse the packet from buffer after receiving it, and before printing.
    2. Your code assumes all packets are TCP, which is not the case. RAW sockets only support Layer 3 protocols (IP, ICMP, etc). In other words, using IPPROTO_TCP is misleading when creating a RAW socket. Stick to IPPROTO_IP, and add the necessary conditions to your code for each protocol you care about (TCP, UDP, etc). This happens to be working because the Linux Kernel validates the protocol number, and fallbacks to IPPROTO_IP. However, this might not work in other systems.
    3. Review if your network communication is using the correct byte-order. The network-byte-order is Big-Endian, while the host-byte-order depends on your architecture, so you may need to convert multi-byte fields back and forth.
    4. Your tcp->seq might have an invalid value, because TCP only accepts values up to 65535, while random() returns values from 0 to RAND_MAX (0x7fffffff). Try tcp->seq = htonl(random() % 65535);
    5. Your offset calculation for the TCP header is incorrect. It should be sizeof(struct iphdr) rather than sizeof(struct tcphdr).
    0 讨论(0)
提交回复
热议问题