C Language Programming---socket basics

Source: Internet
Author: User
Tags terminates htons

The socket was originally developed to support the TCP/IP protocol and is now considered the best way to develop non-rpcwindows network applications.

The socket, as a process communication mechanism for BDS UNIX, is the BSD method for inter-Program Communication (IPC), which means that the socket is used to communicate information to a process and other processes. A socket, often referred to as a socket, is used to describe an IP address and port, which is a handle to a communication chain. Applications typically make requests to the network through sockets or answer network requests.

Development principle:

Server, using ServerSocket to listen to the specified port, the port can be arbitrarily specified (because the port below 1024 is usually reserved port, in some operating systems is not free to use, it is recommended to use a port greater than 1024), waiting for the client connection request, after the client connection, the session generated After completing the session, close the connection.

Client, using the socket to make a connection request to one of the servers on the network, and once the connection is successful, the session is opened and the socket is closed after the session is complete. The client does not need to specify an open port, typically a temporary, dynamic allocation of more than 1024 ports.

--win API Socket

The socket function mentioned in this article, if not specifically stated, refers to the Windows Socket API.

First, WSAStartup function

<span style= "FONT-SIZE:14PX;" >intwsastartup (Wordwversionrequested,lpwsadatalpwsadata);</span>

A program that uses the socket must call the WSAStartup function before using the socket. The first parameter of the function indicates the version of the socket that the program requests to use, where the high byte indicates the secondary version, the low byte indicates the major version, and the operating system returns the version information of the requested socket using the second parameter. When an application calls the WSAStartup function, the operating system searches for the appropriate socket library based on the requested socket version, and then binds the found socket library into the application. The application can then invoke the other socket functions in the requested socket library. The function returns 0 after successful execution.

Example: If a program wants to use the 2.1 version of the socket, then the program code is as follows

<span style= "FONT-SIZE:14PX;" >wversionrequested= Makeword (2, 1); err= WSAStartup (wversionrequested, &wsadata);</span>

Second, WSACleanup function

<span style= "FONT-SIZE:14PX;" >intwsacleanup (void);</span>

After the application finishes using the requested socket library, call the WSACleanup function to unbind the socket library and release the system resources that the socket library occupies.

Third, the socket function

<span style= "FONT-SIZE:14PX;" >socketsocket (Intaf,inttype,intprotocol);</span>

The application calls the socket function to create a socket that can communicate with the network. The first parameter specifies the protocol family of the communication protocol used by the application, and for the TCP/IP protocol family, the parameter is pf_inet; the second parameter specifies the socket type to be created, the stream socket type is sock_stream, and the datagram socket type is SOCK_DGRAM The third parameter specifies the communication protocol used by the application. The function returns the descriptor of the newly created socket if the call succeeds, and returns Invalid_socket if it fails. A socket descriptor is a value of an integer type. There is a Socket descriptor table in the process space for each process, which holds the corresponding relationship between the socket descriptor and the socket data structure. There is one field in the table that holds the descriptor for the newly created socket, and the other field holds the address of the socket data structure, so that its corresponding socket data structure can be found based on the socket descriptor. Each process has a socket descriptor in its own process space but the socket data structure is in the kernel buffer of the operating system. Here is an example of creating a flow socket:

<span style= "FONT-SIZE:14PX;" >structprotoent *ppe;ppe=getprotobyname ("TCP"); Socketlistensocket=socket (Pf_inet,sock_stream,ppe->p_proto);</span>

Four, closesocket function

<span style= "FONT-SIZE:14PX;" >intclosesocket (SOCKETs);</span>

The Closesocket function is used to close a descriptor for the s socket. Since each process has a socket descriptor table, each of the socket descriptors in the tables corresponds to a socket data structure in the operating system buffer, so there may be several socket descriptors pointing to the same socket data structure. There is a single field in the socket data structure that holds the referenced number of the structure, that is, how many socket descriptors point to the structure. When the Closesocket function is called, the operating system checks the value of the field in the socket data structure and, if 1, indicates that only one socket descriptor points to it, so the operating system clears the corresponding table entry in the Socket descriptor table and releases s corresponding socket data structure If the field is greater than 1, the operating system clears only the corresponding table entry in the Socket descriptor table, and the number of references to the socket data structure of s corresponds to minus 1.

The Closesocket function returns 0 if execution succeeds, otherwise returns SOCKET_ERROR.

V. Send function

<span style= "FONT-SIZE:14PX;" >intsend (Sockets,constchar far *buf,intlen,intflags);</span>

        Both client and server applications use the Send function to send data to the other end of the TCP connection. The client program typically sends a request to the server with the Send function, and the server usually sends a reply to the client using the Send function. The first parameter of the function specifies the send-side socket descriptor, the second parameter indicates a buffer that holds the data to be sent by the application, the third parameter indicates the number of bytes of data actually to be sent, and the fourth parameter is generally 0. This describes only the execution flow of the Send function that synchronizes the socket. When the function is called, send compares the length of the data to be sent, Len, and the size of the send buffer of the socket s, and if Len is greater than the length of the send buffer of s, the function returns SOCKET_ERROR, if Len is less than or equal to the length of the send buffer of S, Then send first check whether the protocol is sending the data in the send buffer, if it is waiting for the protocol to send out the data, if the protocol has not begun to send the data in the send buffer or s of the send buffer does not have data, then send compares s of the send buffer of the remaining space and Len, If Len is larger than the remaining space, send waits for the protocol to send the data in the transmit buffer of s, if Len is less than the amount of space left, send will simply copy the data in the BUF to the remaining space (note that it is not the send buffer that sends the data to the other end of the connection). Instead of the protocol, send simply copy the data from the BUF to the remaining space in the send buffer of s). If the Send function copy data succeeds, it returns the number of bytes actually copied, and if send has an error in copy data, then send returns SOCKET_ERROR, if the network is disconnected while the send waits for the protocol to transmit the data. Then the Send function also returns SOCKET_ERROR. Note that the Send function returns the data in the BUF after it has been successfully copied to the remaining space of S's send buffer, but at this point the data is not necessarily immediately passed to the other end of the connection. If the protocol has a network error during subsequent transfers, the next socket function returns SOCKET_ERROR. (Each of the socket functions except for send will have to wait for the data in the socket's send buffer to continue before execution, and if a network error occurs while waiting, the socket function returns SOCKET_ERROR)

Note: Under UNIX systems, if send is disconnected when the network is waiting for the protocol to transmit data, the process that calls send receives a sigpipe signal, and the process terminates the default processing for that signal.

Vi.. recv function

<span style= "FONT-SIZE:14PX;" >INTRECV (Sockets,charfar *buf,intlen,intflags);</span>

Both the client and server applications use the RECV function to receive data from the other end of the TCP connection. The first parameter of the function specifies the receive end socket descriptor, the second parameter indicates a buffer, which is used to hold the data received by the RECV function, the third parameter indicates the length of the buf, and the fourth parameter is generally 0. This describes only the execution flow of the recv function that synchronizes the socket. When the application calls the Recv function, recv waits for the data in the send buffer of s to be passed by the protocol, and if the protocol has a network error while transmitting the data in the send buffer of S, then the RECV function returns SOCKET_ERROR, If there is no data in the transmit buffer of s or after the data has been successfully sent by the protocol, RECV checks the socket s receive buffer, if there is no data in the s receive buffer or the protocol is receiving data, then recv waits until the protocol receives the data. When the protocol takes over the data, the RECV function will copy the data from the receive buffer of S to BUF (note that the data received by the Protocol may be greater than the length of the buf, so in this case a few recv functions are called to copy the data from the receive buffer of S. The recv function is just copy data, the real receive data is the protocol to complete, the RECV function returns the number of bytes it actually copied. If recv errors in copy, it returns SOCKET_ERROR, and if the recv function waits for the protocol to receive data, the network is interrupted, it returns 0.

Note: Under UNIX systems, if the RECV function waits for the protocol to receive data when the network is disconnected, the process that calls Recv receives a sigpipe signal, and the process terminates the default processing for that signal.

Seven, bind function

<span style= "FONT-SIZE:14PX;" >intbind (sockets,conststruct sockaddr far *name,intnamelen);</span>

When a socket is created, there is a default IP address and a default port number in the socket data structure. A service program must call the BIND function to bind it to an IP address and a specific port number. Client programs generally do not have to call the bind function to bind their sockets to IP addresses and break numbers. The first parameter of the function specifies the socket descriptor to bind to, and the second parameter specifies a SOCKADDR structure, which is defined as:

<span style= "FONT-SIZE:14PX;" >structsockaddr {u_shortsa_family;charsa_data[14];}; </span>

sa_family Specifies the address family, and af_inet the socket for the TCP/IP protocol family. When binding a socket on a TCP/IP protocol family, we typically use a different address structure:

<span style= "FONT-SIZE:14PX;" >structsockaddr_in {shortsin_family;u_shortsin_port;structin_addr sin_addr;charsin_zero[8];}; </span>

Where Sin_family af_inet;sin_port indicates the port number; There is only one unique field s_addr in the sin_addr struct that represents the IP address, which is an integer and is generally used as a function inet_ Addr () converts an IP address in the form of a string into an integer value of unsigned long and then resets to S_ADDR. Some servers are multi-host, there are at least two network cards, then the service program running on such a server can put htonl (inaddr_any) to S_ADDR for its socket, the benefit is that regardless of the network segment of the client program can communicate with the service program If you only bind a fixed IP address to the socket that is running a service program on a multiple host, 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 zeros to make the size of the SOCKADDR_IN structure consistent with the size of the SOCKADDR structure. The following is an example of a bind function call:

<span style= "FONT-SIZE:14PX;" >structsockaddr_in saddr;saddr.sin_family= af_inet;saddr.sin_port= htons (8888); Saddr.sin_addr.s_addr= htonl ( Inaddr_any); Bind (Listensocket, (STRUCTSOCKADDR *) &saddr,sizeof (SADDR));</span>

Viii. Listen function

<span style= "FONT-SIZE:14PX;" >intlisten (SOCKET s, int backlog);</span>

The service program can call the Listen function to make its stream socket s in the listening state. The stream socket s in the listening state maintains a client connection request queue, which accommodates up to a backlog of client connection requests. If the function succeeds, it returns 0, or socket_error if execution fails.

Nine, the Accept function

<span style= "FONT-SIZE:14PX;" >socketaccept (sockets,structsockaddr far *addr,intfar *addrlen);</span>

The service program calls the Accept function to remove the first customer request from the Client connection request queue of the stream socket s in the listening state, and creates a new socket to create the connection channel with the client socket, and if the connection succeeds, returns the descriptor of the newly created socket, The newly created socket is later exchanged for the data with the client socket, and if it fails, returns Invalid_socket. The first parameter of the function specifies a stream socket in the listening state; the operating system uses the second parameter to return the address structure of the newly created socket, and the operating system uses the third parameter to return the length of the address structure of the newly created socket. The following is an example of a call to accept:

<span style= "FONT-SIZE:14PX;" >structsockaddr_in serversocketaddr;intaddrlen;addrlen=sizeof (SERVERSOCKETADDR); Serversocket=accept (Listensocket, (STRUCTSOCKADDR *) &serversocketaddr,&addrlen);</span>


X. Connect function

<span style= "FONT-SIZE:14PX;" >intconnect (sockets,conststruct sockaddr far *name,intnamelen);</span>

The client program calls the Connect function to connect the client socket s to a service socket on a specific port on the computer specified by name. If the connection succeeds, connect returns 0, and if it fails, it returns SOCKET_ERROR. Here is an example:

<span style= "FONT-SIZE:14PX;" >structsockaddr_in Daddr;memset ((void*) &daddr,0,sizeof (daddr));d addr.sin_family=af_inet;daddr.sin_port= Htons (8888);d addr.sin_addr.s_addr=inet_addr ("133.197.22.4"), Connect (Clientsocket, (STRUCTSOCKADDR *) &daddr, sizeof (DADDR));</span>


C Language Programming---socket basics

Related Article

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.