Basic TCP Socket Programming

Source: Internet
Author: User

Socket function

In order to perform network I/O, the first thing a process must do is call the socket function, specify the desired type of communication protocol (TCP using IPV4, UDP with IPv6, UNIX domain byte throttle protocol, etc.)

#include <sys/socket.h>int socket (int family,int type,int protocol);//return: If success is a non-negative descriptor, if error is-1

Where the family parameter indicates the protocol family, which is a constant value as shown in Figure 4-2. This parameter is also often referred to as a protocol domain. The type parameter indicates the socket type, which is a constant value as shown in Figure 4-3. The protocol parameter should be set to one of the protocol type values shown in Figure 4-4, or set to 0 to select the system defaults for the given family and type combinations.

Not all socket family and type combinations are valid, and figure 4-5 gives some valid combinations and corresponding real protocols. The items labeled "Yes" are also valid, but no convenient abbreviations have been found, and blank entries are invalid combinations.

4-1 sockets for basic TCP client/service programs

The socket function successfully returns a small nonnegative integer value similar to the file descriptor, which we call the socket descriptor (socket descriptor), or SOCKFD. To get this socket descriptor, we just specified the protocol family (IPV4, IPv6, or Unix) and socket type (byte stream, datagram, or raw socket). We did not specify a local protocol address or a remote protocol address.

Compare af_xxx and Pf_xxx

The af_ prefix represents the address family, and the pf_ prefix represents the protocol family.

The POSIX specification specifies that the first parameter of the socket function is a pf_ value, while the Af_ value is used for the socket address structure, but it defines only one family value in the addrinfo structure, both for calling the socket function and for the socket address structure

Connect function

The TCP client uses the Connect function to establish a connection to the TCP service.

#include <sys/socket.h>int connect (int sockfd,const struct sockaddr *servaddr,socklen_t addrlen);//return: 0 if successful 1 If an error occurs

SOCKFD is the socket descriptor returned by the socket function, the second, third parameter is a pointer to the socket address structure and the size of the structure, and the socket address structure must contain the IP address and port number of the server.

The client does not have to call the BIND function before calling the function, because if necessary, the kernel determines the source IP address and selects a temporary port number as the source port.

In the case of a TCP socket, calling the Connect function will fire the TCP three-way handshake and return only if the connection is successful or error, where there may be several situations where an error is returned.

(1) If the TCP client does not receive the SYN sub-section response, it returns a etimedout error, for example, when the Connect function is called, the 4.4BSD core sends a SYN, if no response waits for 6s and then sends one, and if there is no response then wait for 24s after the next one, This error is returned if you have not received a response after a total of 75s.

Some systems provide administrative control over the time-out value.

(2) If the response to the customer's SYN is RST (indicating a reset), then the server host does not have a process waiting to connect to it on the port we have established (for example, the server process may not be running). This is a hard error, and the customer immediately returns a econnrefused error as soon as the RST is accepted.

The RST is a TCP subsection that TCP sends when an error occurs. The three conditions for the RST are: The destination is the SYN arrival for a port, but there is no server listening on the port: TCP wants to cancel an existing connection: TCP receives a section on a connection that does not exist at all.

(3) If the customer sends a SYN in the middle of a router to raise a "destination unreachable" (Destination unreachable) ICMP error, it is considered a soft error (soft error). The client host kernel saves this information and continues to send the SYN at the interval described in the first case, and returns the saved message (that is, the ICMP error) as a Ehostunreach or Enetunreach error to the process if the response is not received after a specified time. The following two scenarios are also possible: one based on the forwarding of the local system, there is no path to the remote system at all, and the connect call does not wait at all to return.

Bind function

The BIND function assigns a local protocol address to a socket. For the Internet Protocol, the protocol address is a combination of a 32-bit IPV4 address or a 128-bit IPV6 address and a 16-bit TCP or UDP port number.

#include <sys/socket.h>int bind (int sockfd,const struct sockaddr *myaddr,socklen_t addrlen);//return: 0 If successful, 1 if error

  

The second parameter is a pointer to the protocol-specific address structure, and the third parameter is the length of the address structure. For TCP, calling the BIND function can either specify a port number, specify an IP address, or both, and neither can be specified.

  

Listen function

The Listen function is only called by the TCP server, and it does two things.

(1) When the socket function creates a socket, it is assumed to be an active socket, that is, it is a client socket that will invoke connect to initiate a connection. The Listen function converts an unbound socket into a passive socket, indicating that the kernel should accept connection requests to that socket. Calling listen causes the socket to be swapped from the closed state to the listen state.

(2) The second parameter of this function specifies the maximum number of connections that the kernel should queue for the corresponding socket.

#include <sys/socket.h>int Listen (int sockfd,int backlog);//return: 0 If successful, 1 if an error occurs

This function should usually be called after the socket and bind functions are called, and before the Accept function is called.

To understand the backlog parameters, we must recognize that the kernel maintains two queues for any given listener socket;

(1) The connection queue (incomplete connection queue) is not completed, each of which corresponds to one of the following: A client has been issued concurrently to the server, and the server is waiting to complete the corresponding TCP three-way handshake process. These sockets are in the SYN_RCVD state.

(2) The connection queue (completed connection queue) has been completed, and one of the customers who have completed the TCP three-way handshake process corresponds to one of them. These sockets are in the established state

Whenever an item is created in an unfinished connection queue, the parameters from the listening socket are copied to the connection that is about to be established. The connection creation mechanism is completely automatic and requires no server process intervention.

Accpet function

The Accpet function is called by the TCP server to return the next completed connection from the completed Connection queue team header. If the completed queue is empty, then the process is put to sleep (assuming the socket is the default blocking mode)

#include <sys/socket.h>int accept (int aockfd,struct sockaddr *cliaddr,socklen_t *addrlen);//return: If success is a nonnegative descriptor, 1 If an error occurs

The parameters cliaddr and Addrlen are used to return the protocol address of the connected peer process (customer). Addrlen is a value-result parameter, before calling, we will set the integer value referenced by *addrlen to the length of the socket address structure referred to by CLIADDR, which is the exact number of bytes stored by the kernel within the socket address structure.

If Accpet succeeds, its return value is a completely new descriptor that is automatically generated by the kernel, representing the TCP connection to the returned client. When discussing the Accpet function, we call its first parameter the listener socket (listen Sicket) descriptor (created by the socket and then used as the descriptor for the first parameter of bind and listen), which says its return value is a connected socket (connected SOCKET) Descriptor. It is important to differentiate between these two sockets. A server typically creates only one listener socket, which persists over the lifetime of the server. The kernel creates a connected socket for each client connection accepted by the server process (that is, the TCP three-way handshake process for it is complete). When the server finishes servicing a given customer, the corresponding connected sockets are closed.

This function returns a maximum of three values: one may be a new socket descriptor or an integer that indicates an error, the protocol address of the client process (referred to by the CLIADDR Pointer), and the size of the address (as indicated by the Addrlen pointer). If we are not interested in returning the client agreement address, we can put the cliaddr and addrlen mean values as null pointers.

  

Fork and EXEC functions

Basic TCP Socket Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.