Linux UDP recvfrom: What do I get at the start of my buffer?

binaryBigInt :

What do I get at the start of my buffer in case my call to recvfrom returns a valid amount of bytes (e.g. 1400)?

Do I get an ethhdr? This code doesn't work for example even though I should be receiving UDP-Packets:

void read_packets(struct config *cfg) {

    int64_t read_bytes = recvfrom(cfg->socket_fd, buffer, BUFFER_SIZE, 0, NULL, NULL);
    if(read_bytes == -1) {
        return;
    }

    cfg->stats.amnt_of_packets += 1;
    cfg->stats.amnt_of_bytes += read_bytes;

    struct ethhdr *eth = (struct ethhdr*)(buffer);
    if(ntohs(eth->h_proto) == ETH_P_IP) {
        struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));
        if(iph->protocol == IPPROTO_UDP) {
            /* doesn't work */
        }
    }
}

socket_fd was created as:

cfg->socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
dbush :

Using recvfrom on a UDP socket will only return the payload of the UDP packet, i.e. what the sending end passed to sendto. You won't see the ethernet header, IP header, or UDP header as part of this.

You did however pass NULL values for the last two arguments. These can be used to populate a struct sockaddr_in structure which will contain the IP address and UDP port of the sending side.

Also, if you use recvmsg, you have the ability to get the values of some fields from the IP header such as the destination IP address (useful if the socket is receiving multicast packets), the TOS/DSCP field, or various IP options that may be set.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8386&siteId=1
Recommended