Network programming socket BASIC API detailed

Source: Internet
Author: User
Tags function prototype htons

Socket

The socket is an abstraction layer between the application layer and the transport layer, which abstracts the complex operations of the TCP/IP layer into several simple interfaces to supply the communication in the network with the implemented process.

Socket originated from UNIX, in Unix everything is a document philosophy of the idea, the socket is a "open-read/write-off" mode of implementation, the server and the client each maintain a "file", after the establishment of the connection opened, you can write to their own files to read or read each other's content, Closes the file at the end of the communication.

Socket type

Common sockets are available in 3 different types as follows.
(1) streaming socket (SOCK_STREAM)
Streaming sockets provide reliable, connection-oriented communication flow, and it uses TCP protocol to ensure the correctness and order of data transmission.
(2) Datagram Socket (SOCK_DGRAM)
Datagram sockets define a connectionless service in which data is transmitted through separate messages, which are unordered and are not guaranteed to be reliable or error-free. It uses datagram protocol UDP.
(3) original socket (SOCK_RAW)
The original socket allows direct access to the underlying protocol, such as IP or ICMP, and is powerful but inconvenient to use, mainly for the development of some protocols.

Socket creation and connection

The computer data store has two byte precedence: High byte priority and low byte priority. Data on the Internet is transmitted over the network in high byte order, so the conversion is needed to transfer data over the Internet for machines that store data internally in low byte priority.

Several byte order conversion functions:
Htons ()--"Host to network short"; HTONL ()--"Host to Network Long"
Ntohs ()--"network to Host short"; Ntohl ()--"network to Host Long"
Here, h means "host", N means "network", S is "short", l denotes "long".

int socket (int family, int type, int protocol);
The family specifies the type of the socket: Sock_stream, SOCK_DGRAM, sock_raw;protocol are usually assigned "0".

The socket () call returns an integral socket descriptor that you can use later in the call.
Once you return a socket descriptor via the socket call, you should associate the socket with a port on your computer (often when you are designing a server-side program to call that function). You can then listen for service requests on the port, which the client generally does not need to call.

int bind (int sockfd, struct sockaddr *my_addr, int addrlen);
SOCKFD is a socket descriptor, MY_ADDR is a sockaddr type needle that contains information such as native IP address and port number; Addrlen are often set to sizeof (struct sockaddr). Finally, the point of the bind function is that you can automatically obtain the native IP address and randomly obtain a port number that is not occupied by using the following assignment:
My_addr.sin_port = 0; /* System randomly select an unused port number * *
MY_ADDR.SIN_ADDR.S_ADDR = Inaddr_any; /* Fill in the local IP address * *
By placing the My_addr.sin_port at 0, the function will automatically select an unused port for you to use. Similarly, by placing the my_addr.sin_addr.s_addr as Inaddr_any, the system automatically fills in the native IP address. The bind () function returns 0 when it is successfully invoked, returns "-1" When an error is encountered, and errno to the appropriate error number. Also note that when calling a function, do not normally place the port number to a value less than 1024, because 1~1024 is a reserved port number, and you can use a port number greater than 1024 that is not occupied.

When tying a socket to a TCP/IP protocol family, we typically use another address structure:
struct SOCKADDR_IN
{
Short sin_family;
U_short Sin_port;
struct IN_ADDR sin_addr;
Char Sin_zero[8];
};
Where the sin_family set af_inet;sin_port indicates the port number; SIN_ADDR structure body only has a unique field s_addr, which represents an IP address, which is an integer, generally using a function inet_ Addr () converts an IP address in the form of a string to an integer value of unsigned long and then to S_ADDR. Some servers are multihomed hosts, with at least two network adapters, the service program running on such a server can place htonl (inaddr_any) to s_addr when it binds an IP address to its socket, the benefit of which is that clients on any network segment can communicate with the service program If only a fixed IP address is bound to the socket running on the multihomed host, then only the client program that is on the same network segment as the IP address can communicate with the service program. We populate the Sin_zero array with 0来, so that the SOCKADDR_IN structure is the same size as the SOCKADDR structure. The following is an example of a bind function call:
struct sockaddr_in saddr;
memset ((void *) &saddr,0,sizeof (SADDR));
saddr.sin_family = af_inet;
Saddr.sin_port = htons (8888);
SADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
SADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.22.5"); Binding fixed IP
Bind (Listensocket, (struct sockaddr *) &saddr,sizeof (SADDR));

int listen (int sockfd, int backlog);
SOCKFD is the server-side socket descriptor returned by the socket system call; backlog Specifies the maximum number of requests allowed in the request queue, and incoming connection requests wait in the queue for accept () (see below). Backlog limits the number of requests waiting for a service in the queue, and most system defaults are 20. When listen encounters an error, the return -1,errno is placed as the corresponding error code.

int accept (int sockfd, struct sockaddr *addr, int *addrlen);
SOCKFD is a listening server socket descriptor, addr is usually a pointer to a sockaddr_in variable that holds the client address where the connection request is made; Addrten is usually a pointing value of sizeof (struct SOCKADDR_ In) integer pointer variable. Returns one-1 when an error occurs and sets the corresponding errno value. The Accept () function returns a new socket descriptor for use by this new connection, with the data Send () and recv () operation on the new socket descriptor.

Therefore, server-side programs usually perform function calls in the following order:
Socket (); Bind (); Listen (); /* Accept () goes here * *

The Connect () function is used to establish a TCP connection with a remote server whose function prototype is:
int connect (int sockfd, struct sockaddr *serv_addr, int addrlen);
SOCKFD is the Sockt descriptor for the destination server, and SERV_ADDR is the address of the server-side IP address and port number. Returns-1 when an error is encountered, and the corresponding error code is included in the errno. There is no need to call bind () for client programming, because in this case only know the destination machine's IP address, and the client through which port to establish a connection with the server does not require concern, the kernel will automatically select an unoccupied end confession client to use.

"Connect" for UDP:
1, the program can use connect to implement UDP connection socket, the role is in the UDP socket to remember the destination address and destination port.
2, UDP socket using connect, if the datagram is not connected in the specified address and port, will be discarded. A UDP socket that does not call connect will receive all UDP datagrams arriving at this port, without distinguishing between the source port and the address.

About "bind":
1, the client side of the socket does not need to bind, the kernel will automatically select an unused port for the client to use, if there are more than one available connection (multiple IP), the kernel will select an IP as the priority of the source IP use.
2. If the socket binds to a specific IP and port using bind, the data will be sent from the specified IP and port, whether TCP or UDP.

Socket send and receive data

Send () and recv ()-Data transfer for data transfer on a connection-oriented socket (SOCK_STREAM)

int send (int sockfd, const void *msg, int len, int flags);
SOCKFD is the socket descriptor you want to use to transmit data, and MSG is a pointer to the data you want to send.
Len is the length of the data in bytes. Flags are typically set to 0 (the use of this parameter can be referred to the Man Manual).
The Send () function returns the number of bytes actually sent, possibly less than the data you want to send. Therefore, the return value of Send () needs to be measured. This situation should be handled when the Send () return value does not match Len.

int recv (int sockfd,void *buf,int len,unsigned int flags);
SOCKFD is the socket descriptor that accepts data; BUF is the buffer in which the data is received; Len is the length of the buffer. The flags were also set to 0. Recv () returns the number of bytes actually received, or, when an error occurs, returns-1 and resets the corresponding errno value.

Out-of-band data: Data transmitted over a channel other than a data stream channel, often used for synchronization and control of remote processes. Only 1 byte of Out-of-band data can be sent at a time in TCP.
Sent: Send (SOCK_FD, ' f ', 1,msg_oob);
Receive: Recv (SOCK_FD,&OUT_DATA,1,MSG_OOB); Out-of-band data is stored in Out_data.

SendTo () and Recvfrom ()-Data transfer for data transfer on a disconnected socket (Sock_dgram/sock_raw)

In the connectionless datagram socket, the local socket is not connected to the remote machine, so when you send the data, you should refer to the address of the eyesight, sendto () function prototype:
int sendto (int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to,int);
This function has two more parameters than the Send () function to represent the IP address and port number information of the target machine, and Tolen is often assigned to sizeof (struct sockaddr). The SendTo function also returns the actual byte length of the data being sent or returns 1 if a Send error occurs.

int recvfrom (int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int);
From is a struct sockaddr type variable that holds the IP address and port number of the source machine. Fromlen are often placed as sizeof (struct sockaddr). When Recvfrom () returns, the Fromlen contains the number of bytes of data actually deposited in from. The Recvfrom () function returns the number of bytes received or returns 1 when an error occurs, and the corresponding errno is placed.
It should be noted that when you invoke the Connect () function for the datagram socket, you can also use Send () and recv () for data transfer, but the socket is still a datagram socket and uses the Transport layer's UDP service. But when the data is sent or received, the kernel automatically adds the target and source address information.

Close socket

Close () and shutdown ()--End data transfer
When all the data operations are finished, you can call the close () function to release the socket, stopping any data operations on the socket:

Close (SOCKFD); Close () is an operation on a socket that cannot be accessed by the process after it has been closed.
You can also call the shutdown () function to close the socket. This function allows you to stop data transfers only in one direction, while data transfer in a single direction continues. If you can close the write operation of a socket and allow to continue to accept data on the socket until all data is read. Shutdown is an operation on a TCP connection.

int shutdown (int sockfd,int how);
The meaning of SOCKFD is obvious, and the parameters how can be set to the following values:
0-------is not allowed to continue receiving data
·1-------is not allowed to continue sending data
2-------does not allow you to continue sending and receiving data, all is allowed to call Close ()
Shutdown returns 0 when the operation succeeds, and returns 1 (and the corresponding errno) when an error occurs.

IP DNS and other related functions

in_addr_t inet_addr (const char * strptr);
Converts a string IP address to a IPV4 address structure in_addr value

    char * INET_NTOA (struct in_addr * addrptr);
    Convert IPV4 address structure in_addr value to string IP

    conversion of domain name and IP address:  
    struct hostent *gethostbyname (const char *name);  The
    function returns a struct type named Hostent, which is defined as follows:  
    struct hostent 
     { 
         Char *h_name;        /* Host's official domain name */ 
         Char **h_aliases;    /* A null-terminated host alias array */ 
         int     h_addrtype;  /* return type of address, in the context of the Internet af-inet */ 
          int h_length;       /* Address byte length */ 
          Char **h_addr_list; /* A 0-terminated array containing all the addresses of the host */ 
}; 
     #define H_ADDR H_addr_list[0]/* The first address in h-addr-list/*

    Note: The above three functions are not reentrant if you write the following code: &NBSP
    if (Inet_ntoa (ip1), Inet_ntoa (IP2)) = = 0//Determine if 2 IP addresses are the same
    {
        ...
   } The
    above if condition judgment is always true. When you use the above three functions, the function returns, you need to immediately remove the results to save the return value, otherwise it will be overwritten next call. Because the struct in_addr and struct hostent use the static type when saving.

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.