Analysis of Raw Socket Code for IPPROTO_TCP

The Raw socket code can be viewed at this location. It is seen that the Raw socket does not bind or connect to the destination location. We use “sendto” API to send data to the destination IP address and use “recvfrom” API to receive data on the destination IP address.

The socket is opened with the below socket call.

        raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);

The destination address is chosen to be loopback for this present example. The below code snippets from the sample code show how the destination address is filled up

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

As the protocol field is set to IPPROTO_TCP, the TCP header needs to be added by the application.

The below code snippets achieve the same.

        tcp_hdr->source = htons(SERVPORT);
        tcp_hdr->dest = htons(DESTPORT);
        tcp_hdr->ack_seq = 0x0; /* seq number */
        tcp_hdr->doff = 5; /* data_offset * 4 is TCP header size */
        tcp_hdr->syn = 1; /* SYN flag */
        tcp_hdr->window = htons(200); /* Window size scaling*/

The checksum is calculated for TCP header and filled. 

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

The TCP header so developed is sent to the destination address alongwith the data via the “sendto” API.

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

The received packet will contain the IP header + TCP header formed by the application + data. It is retrieved via the “recvfrom” API.

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

The wireshark output of the transmitted packet is shown below

The output of the program is shown below. Note that the program has to be either run in root mode or the permission CAP_NET_RAW has to be set as shown below

The “ss -w -a” shell command displays the raw socket as shown below

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

Raw Socket Code Example for IPPROTO_UDP

Comments

  1. Pingback: Raw Socket code with IPPROTO_TCP Protocol | Hitch Hiker's Guide to Learning

Leave a Reply

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