|
RAW sockets allows you to bypass the TCP/UDP layer (Layer 4) in the RtxTcpIp 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.
With the current implementation, only one raw socket can be opened per device at any given time. To create a raw socket, the type field should be set to SOCK_RAW and the protocol field should be IPPROTO_RAW:
sock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
An application must use sendto to send datagrams on a raw socket. Also, for the current implementation, 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.
char sendbuf[maxsize]; char recvbuf[maxsize]; char *Iphdr = sendbuf; sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 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);
See RawSockets in this guide for information about the RAW socket sample shipped with RTX.