[ Team LiB ] Previous Section Next Section

28.2 Raw Socket Creation

The steps involved in creating a raw socket are as follows:

  1. The socket function creates a raw socket when the second argument is SOCK_RAW. The third argument (the protocol) is normally nonzero. For example, to create an IPv4 raw socket we would write

    
    
    int     sockfd;
    
    sockfd = socket(AF_INET, SOCK_RAW, protocol);
    
    
    

    where protocol is one of the constants, IPPROTO_xxx, defined by including the <netinet/in.h> header, such as IPPROTO_ICMP.

    Only the superuser can create a raw socket. This prevents normal users from writing their own IP datagrams to the network.

  2. The IP_HDRINCL socket option can be set as follows:

    
    
    const int on = 1;
    
    if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0)
        error
    
    
    

    We will describe the effect of this socket option in the next section.

  3. bind can be called on the raw socket, but this is rare. This function sets only the local address: There is no concept of a port number with a raw socket. With regard to output, calling bind sets the source IP address that will be used for datagrams sent on the raw socket (but only if the IP_HDRINCL socket option is not set). If bind is not called, the kernel sets the source IP address to the primary IP address of the outgoing interface.

  4. connect can be called on the raw socket, but this is rare. This function sets only the foreign address: Again, there is no concept of a port number with a raw socket. With regard to output, calling connect lets us call write or send instead of sendto, since the destination IP address is already specified.

    [ Team LiB ] Previous Section Next Section