Linux TCP

process

The server side

  1. In Linux, a socket is considered a file and is manipulated using a file descriptor. First, a variable is defined to store the file descriptor of the socket: sockfd. Create a socket with the following function: sockfd = socket(AF_INET,SOCK_STREAM,0);

    int socket (int __domain, int __type, int __protocol); / / return sockfdCopy the code
    • Int __domain: indicates the protocol domain, AF_INET(IPV4), AF_INET6(IPV6), AF_LOCAL (or AF_UNIX, Unix domain socket), or AF_ROUTE. The protocol domain determines the TYPE of the SOCKET IP address.
    • Int __type: specifies the SOCKET type, including SOCK_STREAM and SOCK_DGRAM.
    • Int __protocol: specifies the protocol. The default protocol is 0. If type is data flow, the default protocol is TCP, and the default protocol is UDP for packets
  2. The binding

        int bind (int __fd, const struct sockaddr * __addr, socklen_t __len)
    Copy the code
    • Int __fd Socket file descriptor

    • Struct sockaddr * __addr IP address const struct sockaddr * __addr IP address const struct sockaddr * __addr IP address

      Ipv4 corresponds to:

         struct sockaddr_in {
            sa_family_t    sin_family; /* address family: AF_INET */
            in_port_t      sin_port;   /* port in network byte order */
            struct in_addr sin_addr;   /* internet address */
        };
      
        /* Internet address. */
        struct in_addr {
            uint32_t       s_addr;     /* address in network byte order */
        };
      Copy the code

      Ipv6 corresponds to:

      struct sockaddr_in6 { sa_family_t sin6_family; /* AF_INET6 */ in_port_t sin6_port; /* port number */ uint32_t sin6_flowinfo; /* IPv6 flow information */ struct in6_addr sin6_addr; /* IPv6 address */ uint32_t sin6_scope_id; /* Scope ID (new in 2.4) */; struct in6_addr { unsigned char s6_addr[16]; /* IPv6 address */ };Copy the code
    • Socklen_t __len Specifies the address length

  3. Listening to the

    Open the corresponding port, start listening, non-blocking. /* Prepare to accept connections on socket FD. N connection requests will be queued before further requests are refused. Returns 0 on success, -1 for errors. */ int listen (int __fd, int __n)

    • Fd file descriptor
    • N Maximum number of connections that can be queued on the corresponding socket
  4. accept()

    Receives the TCP request and completes the three-way handshake

     accept (int __fd, struct sockaddr * __addr, socklen_t *__restrict __addr_len);
    Copy the code
    • The socket on which fd listens
    • Addr Passes in the pointer and passes out the address information of the client
    • Len Addr length

    Accept blocks by default until a client connection is established and returns a newly available socket. This socket is a connection socket.

    At this point we need to distinguish between two types of sockets,

    • Listen socket: Listen socket like the accept parameter sockfd, this is a listen socket generated after the server starts calling the socket() function. This is called the listen socket description.

    • Connect socket: A socket changes from an active connect socket to a listening socket. The Accept function returns the connected socket descriptor (a connection socket), which represents a dot connection that already exists on the network.

    A server usually only creates a listening socket descriptor that lasts for the life of the server. The kernel creates a connected socket descriptor for each client connection accepted by the server process. When the server finishes serving a client, the corresponding connected socket descriptor is closed.

  5. Reading and writing communication

    This section is a TCP connection, so you can use write and read to communicate through file descriptors. In addition, you can also use the send() and recv() functions provided by sockets to communicate.

    function Added features
    write The simplest socket writing function
    send Added flags
    sendto Added socket address and socket length parameters
    writev No markup or socket address, but decentralized writing capability
    sendmsg Added markup, socket address and length, ability to scatter write and attached data
  6. Closing connections The connection socket needs to be closed, and when the service is terminated, close(fd) is called to close the connection socket. The header file unistd.h.

The client

  1. Create a socket

  2. Connect () creates a connection

     /* Open a connection on socket FD to peer at ADDR (which LEN bytes long).
        For connectionless socket types, just set the default address to send to
        and the only address from which to accept transmissions.
        Return 0 on success, -1 for errors.
    
        This function is a cancellation point and therefore not marked with
        __THROW.  */
     extern int connect (int __fd, const struct sockaddr * __addr, socklen_t __len);
    Copy the code
    • Fd: indicates the newly created socket
    • Addr: structure of sockaddr_in or sockaddr_in6
    • Len: The length of the second argument
  3. Read and write operations

Auxiliary function

  1. IP address-related functions

    1. inet_pton

       /* Convert from presentation format of an Internet number in buffer
          starting at CP to the binary network format and store result for
          interface type AF in buffer starting at BUF.  */
          int inet_pton (int __af, const char * __cp,
                     void *  __buf)
      Copy the code
      • Af: IP type AF_INET, AF_INET6, AF_LOCAL…
      • Cp: indicates an IP address in dotted decimal notation
      • Buf: The pointer to the binary IP address is passed &servaddr.sin_addr.sin_addr

      If the function fails, it returns a negative value and sets errno to EAFNOSUPPORT. If the af argument specifies the wrong address family and cp format, the function returns 0.

    2. inet_ntop

      /* Convert a Internet address in binary network format for interface type AF in buffer starting at CP to presentation form and place result in buffer of length LEN astarting at BUF. */ const char *inet_ntop (int __af, const void * __cp, Char * __buf, socklen_t __len) is the opposite of the above functionCopy the code
  2. Byte stream correlation function

    /* Functions to convert between host and network byte order. Please note that these functions normally take `unsigned long int' or `unsigned short int' values as arguments and also return them. But this was a short-sighted decision since on different systems the types may have different representations but the values are always the same. */ extern uint32_t  ntohl (uint32_t __netlong) __THROW __attribute__ ((__const__)); extern uint16_t ntohs (uint16_t __netshort) __THROW __attribute__ ((__const__)); extern uint32_t htonl (uint32_t __hostlong) __THROW __attribute__ ((__const__)); extern uint16_t htons (uint16_t __hostshort) __THROW __attribute__ ((__const__));Copy the code