Basic TCP socket Functions

Source: Internet
Author: User
The following describes the basic TCP socket functions. 1. Socket Functions
Specifies the expected communication protocol type.
  1. # Include <sys/types. h>/* See Notes */
  2. # Include <sys/socket. h>
  3. Int socket (INT domain, int type, int Protocol );
  4. Return: if the operation succeeds, it is a non-negative descriptor, and if the operation fails, it is-1.
 
Parameter description:
Domain: Specifies the protocol family, also known as the Protocol domain, which is a common value.
Af_inet IPv4 protocol
Af_inet6 IPv6 protocol
Af_local/af_unix UNIX protocol domain
Af_route route socket
Af_key key socket

Type: Specifies the socket type.
Sock_stream byte stream socket
Sock_dgram datagram socket
Sock_seqpacket ordered grouping socket
Sock_raw original socket

Protocol: indicates the protocol type. Generally, the value is 0, which is used to select the system default value of the given domain and type combination.
Ipproto_tcp TCP transmission protocol
Ipproto_udp UDP transmission protocol
Ipproto_sctp sctp transmission protocol
Function Description:
When the socket function succeeds, it returns a small non-negative integer value, which is similar to the file descriptor. We call it a socket.
Descriptor, or sockfd for short. To obtain this socket descriptor, we only specify the protocol family (IPv4, IPv6
Or UNIX) and socket type (byte stream, datagram, or original socket ). We have not specified a local or remote
Protocol address.

2. Connect Function 
TCP customers use the connect function to establish a connection with the TCP server.
  1. # Include <sys/socket. h>
  2. Int connect (INT sockfd, const struct sockaddr * servaddr, socklen_t addrlen );
  3. Return Value: 0 if successful, and-1 if an error occurs.

Parameter description:
Sockfd: Socket descriptor returned by the socket function.
Servaddr and addrlen: the pointer to a socket address structure and the size of the structure. Socket address Structure
It must contain the IP address and port number of the server.
Function Description:
The customer does not have to call the BIND function before calling the connect function. If necessary, the kernel will determine the source
And select a temporary port as the source port. Therefore, the socket in the customer process generally only needs to specify the customer
The IP address and port number of the server to be connected.
 
If it is a TCP socket, calling the connect function will trigger the TCP three-way handshake. And only when the connection is successful or
Returned only when an error occurs. Errors are as follows:
1-> the tcp client does not receive the SYN subnode response.
2-> the response of the TCP server to the customer's SYN segmentation is RST.
3-> an error occurs on a vro due to the SYN subnode sent by the customer.
 
If the Connect call fails, the socket is no longer available and must be closed. We cannot execute such a socket again.
Connect function.

3. Bind Functions
Assign a local Protocol address to a socket. For Internet protocols, the Protocol address is a 32-bit IPv4 address and 128
A combination of IPv6 addresses and 16-bit TCP or UDP port numbers. The BIND function is mainly used on the server to specify the local
Which network interface of the host (IP address, which can be inaddr_any, indicating any network interface of the local host) can accept the customer
The request and the specified port number (that is, the process that is enabled waiting for the client to connect ).
 
  1. # Include <sys/socket. h>
  2. Int BIND (INT sockfd, const struct sockaddr * myaddr, socklen_t addrlen );
  3. Return Value: 0 if successful, and-1 if an error occurs.
Parameter description:
Sockfd: Socket descriptor returned by the socket function.
Myaddr and addrlen: pointer to a socket address structure and the size of the structure.
 
Function Description:
For TCP, you can call the BIND function to specify a port number, an IP address, or both.
You can leave this parameter unspecified.
 
The server binds their well-known port numbers at startup (how to bind them ?). If a tcp client or server has not called
Bind binds a port. When connect or listen is called, the kernel selects a temporary port for the corresponding socket.
Enabling the kernel to select a temporary port is normal for TCP customers, unless the application requires a reserved port. However, for TCP services
It is extremely rare because servers are known by their well-known port numbers.
 
A process can bind a specific IP address to its socket, but this IP address must belong to the network interface of its host
1 (for TCP servers ). For TCP customers, This assigns the source IP address (Server
Source Address ). For a TCP server, this means that the socket will only receive client connections whose destination is the IP address. TCP socket
Generally, the IP address is not bound to its socket. When a socket is connected, the kernel selects the source IP address based on the outbound network interface used.
The outbound port used depends on the path to the server. If the TCP server does not bind the IP address to it
The kernel uses the destination IP address of the sent SYN as the source IP address of the server (that is, the IP address of the server is equal to the status of inaddr_any ).
In fact, the customer's source IP address is the server's destination address, and the server's source IP address is the customer's destination address.
There are two IP addresses: the customer IP address and the server IP address. 4. Listen Function
  1. # Include <sys/socket. h>
  2. Int listen (INT sockfd, int backlog );
  3. Return Value: 0 if successful, and-1 if an error occurs.
Function Description:
The listen function is called only by the TCP server. It does two things.
(1) convert an unconnected socket (active) into a passive socket, indicating that the kernel should accept the request for connection pointing to the socket.
(2) The backlog parameter specifies the maximum number of connections that the kernel should queue for the corresponding socket. The kernel always maintains two
Queue.
(1) The connection queue is not completed, and each SYN is segmented for one of them:
The TCP three-way handshake process has been sent by a customer and reached the server, while the server is waiting for completion. These sockets are in the syn_rcvd state.
(2) connection queue completed
Each customer who has completed the TCP three-way handshake corresponds to one of them. These sockets are in the established state.
Backlog is the maximum value of the two queues.
After the three-way handshake is complete, the data that arrives before the server calls accept should be queued by the TCP server, and the maximum data volume is the size of the receiving buffer of the connected socket. 5. Accept Function
The accept function is called by the TCP server to return the next completed connection from the completed connection queue header. If the completed queue is empty, the process is put into sleep (assuming that the socket is the default blocking method ).
  1. # Include <sys/socket. h>
  2. Int accept (INT sockfd, struct sockaddr * cliaddr, socklen_t * addrlen );
  3. Return: if the operation succeeds, the non-negative connected Descriptor and the IP address and port number of the Peer end are returned. If the operation succeeds, the error is-1.
Parameter description:
Cliaddr and addrlen are used to return the Protocol addresses of connected peer processes (customers. Before the call, we will
The referenced integer is set to the length of the socket address structure referred to by cliaddr. When returned, the integer is stored in the socket by the kernel.
The exact number of bytes in the address mechanism.
Function Description:
If the Accept call is successful, the returned value is a brand new descriptor automatically generated by the kernel, representing TCP
Connection. When discussing the accept function, we call it the first parameter as the listener socket Descriptor (created by the socket and then used as the descriptor of the first parameter of bind and listen ), the returned value is the connected socket descriptor. It is very important to distinguish these two sockets. A server generally creates only one listening socket, which exists throughout the life cycle of the server. The kernel creates a connected socket for the client connection accepted by each server process (that is, the TCP three-way handshake process has been completed ). When the server completes the service for a connected customer, the corresponding connected socket will be closed.

6. Fork Functions
Is the only way to send new processes in UNIX.
 
  1. # Include <unistd. h>
  2. Pid_t fork (void );
  3. Return Value: 0 for the child process, and-1 for the parent process.

Function Description:
Fork calls are returned twice. It is returned once in the calling process (parent process). The returned value is a new Derived Process (child process)
The ID of the sub-process. The return value is 0. Therefore, the returned value indicates whether the current process is a child process or a parent process.
Process.
The reason fork returns 0 in the child process instead of the parent process ID is that any child process has only one parent process, and the child process
You can always call getppid to obtain the ID of the parent process. On the contrary, a parent process can have many sub-processes. And cannot pass
Function call to obtain the ID of the sub-process. If the parent process wants to track the process IDs of all child processes, it must record each time
The Return Value of the fork call. The current process can be called by the getpid system to obtain its own process ID.
All descriptors opened before the fork is called in the parent process are shared by the child process after the fork is returned. The data segment will be copied.
Instead of sharing.
Two typical fork calls:
(1) A process creates a copy of itself, so that each copy can process its own
Operation. This is a typical usage of network servers.
(2) One process wants to execute another program. Since the only way to create a new process is to call fork, the process first calls fork to create a copy of itself, and then one of the copies calls exec to replace itself with a new program. This is a typical usage of shell-like programs.

6. Exec function family
An exec function can replace the current process with a new process, which is specified by the path or file parameter.
  1. # Include <unistd. h>
  2. Extern char ** environ;
  3. Int execl (const char * path, const char * Arg ,...);
  4. Int execlp (const char * file, const char * Arg ,...);
  5. Int execle (const char * path, const char * Arg,
  6. ..., Char * const envp []);
  7. Int execv (const char * path, char * const argv []);
  8. Int execvp (const char * file, char * const argv []);
  9. Int execve (const char * path, char * const argv [], char * const envp []);
  10. Return: if the request is successful, no value is returned. If the request fails, the value is-1.

Function Description:
The difference between the Six exec functions is: (a) whether the file name of the program to be executed is specified by the file or by the path; (B) the parameters of the new program are listed one by one or referenced by a pointer array. (c) Whether to pass the environment of the calling process to the new program or specify a new environment for the new program. These functions only return to the caller when an error occurs. Otherwise, control is passed to the starting point of the new program. It is usually the main function. Generally, execve is a system call in the kernel, and the other five are the library functions that call execve.
 
7. getsockname and getpeername Functions
  1. # Include <sys/socket. h>
  2. Int getsockname (INT sockfd, struct sockaddr * localaddr, socklen_t * addrlen );
  3. Int getpeername (INT sockfd, struct sockaddr * peeraddr, socklen_t * addrlen );
  4. Return: if the request is successful, no value is returned. If the request fails, the value is-1.
The two functions return the local Protocol address (getsockname) associated with a socket, or the field negotiated address (getpeername) associated with a socket ).

Basic TCP socket Functions

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.