Maddy
Maddy

Reputation: 1389

Determining if a packet if type IPv4 or IPv6

I have a user-space application that receives an IP packet. It needs to determine if the packet is of type v4 or v6. Assuming 'buffer' contains the packet, I have thought of two approaches:

  1. void *check_header(void *buffer) {
    struct iphdr *iph = (struct iphdr *)buffer;
    if (iph->version == IPV4) {
        /* IPv4 */
    } else if (iph->version == IPV6) {
        /* IPv6 */
    }
    ......
    }
    
    1. Find out the endianness of the machine.
    2. Access the version field in the packet accordingly.

Is there a better way to figuring out the packet type?

Upvotes: 0

Views: 1194

Answers (1)

abligh
abligh

Reputation: 25189

The IP version field is the bottom 4 bits of the first byte. As this is in a byte (rather than a multibyte) field, the endianness of the machine should be irrelevant. You will need it, however, for multibyte structures.

Upvotes: 1

Related Questions