Analysis of RAW socket IPPROTO_UDP code

The Raw socket code based on UDP protocol can be seen at this Link. We directly send the packet to the destination address via “sendto” API. As was seen in the TCP code for Raw sockets, we need to create the UDP header in the application and send the header alongwith the packet data.

The socket is opened via the socket API as shown below

        raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_UDP));

The client address to send the packet to is the loop-back address and hence we also listen on the same loop-back address to receive the packet. The code snippet is shown below

        clientaddr->sin_family = AF_INET;
        clientaddr->sin_port = htons(DESTPORT);
        clientaddr->sin_addr.s_addr = inet_addr(“127.0.0.1”);

The UDP header is filled in by the application. The UDP header is an 8 byte header.

        udp_hdr = (struct udphdr *)buffer; 

        udp_hdr->source = htons(SERVPORT);
        udp_hdr->dest = htons(DESTPORT);
        udp_hdr->len = htons(sizeof(struct udphdr));

Checksum is calculated as per pseudo header. Check the code for the same.

        udp_hdr->check = (in_cksum((unsigned short *) csum_buffer,
(sizeof(struct pseudo_iphdr)+ sizeof(struct udphdr) + strlen(string_data) + 1)));

The “sendto” API is used to send the data and the “recvfrom” API is used to receive the data on the loop-back interface. The code snippet is shown below

sendto(raw_socket, buffer,(sizeof(struct udphdr)+strlen(string_data)+1), 0,
(struct sockaddr *)clientaddr, sizeof(struct sockaddr_in));

recvfrom(raw_socket, recvbuffer,(sizeof(struct iphdr) + sizeof(struct udphdr)+strlen(string_data)+1), 0, (struct sockaddr *)clientaddr, &length);

The wireshark capture is shown below

The output on the receive side is shown below

The output from the “ss -w -a” shell command provides the below output

State         Recv-Q   Send-Q     Local Address:Port      Peer Address:Port
UNCONN     0            0                0.0.0.0:udp                          0.0.0.0:*

Using Connect and Bind on a Raw Socket

Comments

  1. Pingback: Raw Socket Code with IPPROTO_UDP protocol | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *