Using RAW Sockets
RAW sockets allows you to bypass the TCP/UDP layer (Layer 4) in the RT-TCP/IP stack and communicate directly with the Network IP layer (Layer 3). This functionality allows you to skip the addition of TCP/UDP protocols to your frames and, optionally, provide a comparable protocol of your own.
To create a raw socket, you must use the socket function and set the type field to SOCK_RAW. The protocol field can be set to any value above IP layer, such as IPPROTO_ICMP and IPPROTO_IGMP. Protocols that are not allowed are IPPROTO_UDP and IPPROTO_TCP. For example:
sock = socket (AF_INET, SOCK_RAW, SOMEPROTO);
An application must use sendto to send datagrams on a raw socket. The application must build the entire IP datagram, including the IP header. No processing is performed by the IP layer on a raw Ethernet socket except for setting the IP header checksum bit to 0. This lets the stack, versus the application, calculate the checksum and populate the IP header checksum value accordingly.
An application must use recvfrom to read datagrams from a raw socket. Before you can receive packets on a raw socket, you must bind the socket to the IP address of the interface on which you want to receive packets.
The following pseudo code shows you how to create the socket, define the IP header, and send and receive using the socket.
#define SOMEPROTO = 123;
char sendbuf[maxsize]; char recvbuf[maxsize]; char *Iphdr = sendbuf; sock = socket(AF_INET, SOCK_RAW, SOMEPROTO);
Iphdr[0] = version IPhdr[1] = Internet header length IPhdr[2] = Type of Service IPhdr[3] = Total Length IPhdr[4] = Identification IPhdr[5] = Flags IPhdr[6] = Fragment Offset IPhdr[7] = Time to Live IPhdr[8] = Protocol IPhdr[9] = Header Checksum IPhdr[10] = Source IP address IPhdr[11] = destination IP address bind(sock, (sockaddr*) & sendaddr, sizeof(sendaddr);
if (transmit) len = sendto(sock, sendbuf, sizeof(sendbuf), 0,(SOCKADDR *) &pFrom, iFromSize); else len = recvfrom(sock, recvbuf, sizeof(recvbuf), 0,(SOCKADDR *) &pFrom, &iFromSize);
Related topics: