TCP (sockets) programming C/C ++ implementation

Source: Internet
Author: User

Communication

Server: </p> <p> # pragma comment (lib, "ws2_32.lib") <br/> # include <Winsock2.h> <br/> # include <stdio. h> </p> <p> void main () <br/> {<br/> // version negotiation <br/> WORD wVersionRequested; <br/> WSADATA wsaData; <br/> int err; </p> <p> wVersionRequested = MAKEWORD (0101); // 0 x <br/> err = WSAStartup (wVersionRequested, & wsaData ); </p> <p> if (err! = 0) <br/>{< br/> return 0; <br/>}</p> <p> if (LOBYTE (wsaData. wVersion )! = 1 | HIBYTE (wsaData. wVersion )! = 1) // wsaData. wVersion! = 0x0101 <br/>{< br/> WSACleanup (); <br/> return 0; <br/>}</p> <p> // create a Socket <br/> SOCKET sockSvr = socket (AF_INET, SOCK_STREAM, 0 ); </p> <p> // create an IP address and port <br/> SOCKADDR_IN addrSvr; </p> <p> addrSvr. sin_addr.S_un.S_addr = htonl (INADDR_ANY); <br/> addrSvr. sin_family = AF_INET; <br/> addrSvr. sin_port = htons (6000); </p> <p> // bind a port listener <br/> bind (sockSvr, (SOCKADDR *) & addrSvr, sizeof (SOCKADDR )); <br/> listen (sockSvr, 5 ); </P> <p> sockaddr_in addrClient; <br/> int len = sizeof (sockaddr); </p> <p> while (true) <br/> {<br/> // blocking method to obtain a client Socket connection <br/> SOCKET sockConn = accept (sockSvr, (sockaddr *) & addrClient, & len); <br/> char sendbuffer [128]; <br/> sprintf (sendbuffer, "Welcom % s! ", Inet_ntoa (addrClient. sin_addr); </p> <p> // send data to the client Socket <br/> send (sockConn, sendbuffer, strlen (sendbuffer) + ); <br/> char recvbuffer [128]; </p> <p> // receives data from the customer's Soc <br/> recv (sockConn, recvbuffer, 0 ); <br/> printf ("% s/n", recvbuffer); </p> <p> // disable Socket <br/> closesocket (sockConn ); <br/>}</p> <p> closesocket (sockSvr); </p> <p> // release Winsock resources <br/> WSACleanup (); <br/> return 0; <br/>}</p> <p> client: </p> <p> # Pragma comment (lib, "ws2_32.lib") <br/> # include <Winsock2.h> <br/> # include <stdio. h> </p> <p> void main () <br/> {<br/> // version negotiation <br/> WORD wVersionRequested; <br/> WSADATA wsaData; <br/> int err; </p> <p> wVersionRequested = MAKEWORD (0101); // 0 x <br/> err = WSAStartup (wVersionRequested, & wsaData ); </p> <p> if (err! = 0) <br/>{< br/> return 0; <br/>}</p> <p> if (LOBYTE (wsaData. wVersion )! = 1 | HIBYTE (wsaData. wVersion )! = 1) // wsaData. wVersion! = 0x0101 <br/>{< br/> WSACleanup (); <br/> return 0; <br/>}</p> <p> // create a SOCKET connecting to the server <br/> socket sock = SOCKET (AF_INET, SOCK_STREAM, 0 ); </p> <p> // create an address. <br/> SOCKADDR_IN hostAddr; <br/> hostAddr. sin_addr.S_un.S_addr = inet_addr ("127.0.0.1"); <br/> hostAddr. sin_family = AF_INET; <br/> hostAddr. sin_port = htons (6000); </p> <p> // connect to the server <br/> connect (sock, (sockaddr *) & hostAddr, sizeof (sockaddr )); </p> <p> char revBuf [128]; </p> <p> // obtain data from the server <br/> recv (sock, revBuf, 0 ); <br/> printf ("% s/n", revBuf); </p> <p> // send data to the server <br/> send (sock, "Hello Host! ", 12, 0); </p> <p> closesocket (sock); <br/> return 0; <br/>}</p> <p>

-----------------------------------------------

This article is some of my experiences in MS-Windows and HP-Unix network programming. It is for your reference only. If the Socket function mentioned in this article is not specifically described, it refers to the Windows Socket API.

1. WSAStartup Function
Int WSAStartup (
WORD wVersionRequested,
LPWSADATA lpWSAData
);
The program using the Socket must call the WSAStartup function before using the Socket. The first parameter of this function indicates the Socket version requested by the program. The high byte indicates the secondary version and the low byte indicates the primary version; the operating system uses the second parameter to return the request's Socket version. When an application calls the WSAStartup function, the operating system searches for the corresponding Socket Library Based on the requested Socket version, and then binds the Socket Library to the application. In the future, the application can call other Socket functions in the requested Socket library. After the function is successfully executed, 0 is returned.
For example, if a program uses a Socket of Version 2.1, the program code is as follows:
WVersionRequested = MAKEWORD (2, 1 );
Err = WSAStartup (wVersionRequested, & wsaData );

Ii. WSACleanup Function
Int WSACleanup (void );
After the application completes the use of the requested Socket library, it needs to call the WSACleanup function to unbind from the Socket library and release the system resources occupied by the Socket library.

Iii. socket Functions
Socket socket (
Int AF,
Int type,
Int Protocol
);
The application calls the socket function to create a socket capable of network communication. The first parameter specifies the protocol family used by the application. For the TCP/IP protocol family, this parameter is set to 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. This function returns the descriptor of the newly created socket if the call is successful, and invalid_socket if the call fails. The socket descriptor is an integer value. Each process has a socket Descriptor Table in the process space, which stores the correspondence between the socket Descriptor and the socket data structure. In this table, one field stores the descriptor of the newly created socket, and the other field stores the address of the socket data structure. Therefore, the corresponding socket data structure can be found based on the socket descriptor. Each process has a socket Descriptor Table in its own process space, but the socket data structure is in the kernel buffer of the operating system. The following is an example of creating a stream socket:
Struct protoent * PPE;
PPE = getprotobyname ("TCP ");
Socket listensocket = socket (pf_inet, sock_stream, PPE-> p_proto );

Iv. closesocket Functions
Int closesocket (
Socket s
);
The closesocket function is used to close a socket whose descriptor is s. Each process has a socket Descriptor Table. Each socket descriptor in the table corresponds to a socket Data Structure located in the operating system buffer, therefore, several socket descriptors may point to the same socket data structure. There is a field in the socket data structure that stores the number of times this structure is referenced, that is, how many socket descriptors point to this structure. When the closesocket function is called, the operating system first checks the value of this field in the socket data structure. If it is 1, it indicates that only one socket descriptor points to it, therefore, the operating system first clears the entry corresponding to s in the socket Descriptor Table and releases the socket data structure corresponding to s. If this field is greater than 1, then, the operating system only clears the corresponding table items of s in the socket Descriptor Table, and reduces the number of references to the socket data structure of s by 1.
If the closesocket function is successfully executed, 0 is returned; otherwise, SOCKET_ERROR is returned.

5. send Function
Int send (
SOCKET s,
Const char FAR * buf,
Int len,
Int flags
);
Both the client and server applications use the send function to send data to the other end of the TCP connection. The client program generally uses the send function to send requests to the server, while the server uses the send function to send responses to the client program. The first parameter of this function specifies the sender socket descriptor. The second parameter specifies a buffer zone for storing data to be sent by the application. The third parameter specifies the number of bytes of data to be sent; the fourth parameter is usually set to 0. Only the execution process of the send function for Synchronous Socket is described here. When this function is called, send first compares the length of the data to be sent len and the length of the sending buffer of socket s. If len is greater than the length of the sending buffer of s, the function returns SOCKET_ERROR; if len is smaller than or equal to the length of the sending buffer of s, send first checks whether the protocol is sending data in the sending buffer of s. If yes, wait for the Protocol to finish sending the data, if the Protocol has not started sending data in the sending buffer of s or there is no data in the sending buffer of s, send will compare the remaining space in the sending buffer of s and len, if len is larger than the size of the remaining space, send will wait for the Protocol to finish sending data in the s sending buffer, if len is smaller than the size of the remaining space, send only copies the data in the buf to the remaining space (note that it is not sending the data in the sending buffer of s to the other end of the connection, instead, send only copies the data in the buf to the remaining space in the sending buffer of s ). If the send function successfully copies the data, the actual number of bytes of copy is returned. If an error occurs during sending data copy, the send function returns SOCKET_ERROR; if the network is disconnected when sending data while waiting for the Protocol to send data, the send function also returns SOCKET_ERROR. Note that the send function successfully copies the data in the buf to the remaining space of the s sending buffer, and then returns the data. However, the data is not necessarily uploaded to the other end of the connection immediately. If a network error occurs during subsequent transmission, the next Socket function will return SOCKET_ERROR. (Each Socket function except send must wait for the data in the Socket sending buffer to be transmitted by the protocol before execution. If a network error occurs while waiting, then the Socket function will return SOCKET_ERROR)
Note: In Unix systems, if the network is disconnected when sending data while waiting for the send protocol, the process that calls send receives a SIGPIPE signal. The process processes the signal by default and terminates the process.

Vi. recv Functions
Int Recv (
Socket s,
Char far * Buf,
Int Len,
Int flags
);
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 receiver socket descriptor. The second parameter specifies a buffer zone used to store the data received by the Recv function. The third parameter specifies the length of the Buf; the fourth parameter is usually set to 0. Only the execution process of the Recv function for Synchronous socket is described here. When the application calls the Recv function, the Recv waits for the data in the s sending buffer to be transmitted by the Protocol. If the Protocol encounters a network error when sending data in the s sending buffer, then the Recv function returns socket_error. If no data is in the sending buffer of s or the data is successfully sent by the protocol, the Recv first checks the receiving buffer of socket S, if there is no data in the s receiving buffer or the Protocol is receiving data, the Recv waits until the Protocol receives the data. When the Protocol receives the data, the Recv function copies the data in the s receiving buffer to the Buf (note that the data received by the protocol may be larger than the length of the Buf, in this case, you need to call the Recv function several times to copy the data in the s receiving buffer. The Recv function only copies data, and the real data reception is completed by the Protocol). The Recv function returns the actual number of bytes of the copy. If a Recv error occurs during copy, socket_error is returned. If the Recv function is interrupted while waiting for the Protocol to receive data, 0 is returned.
Note: In Unix systems, if the network is disconnected when the Recv function is waiting for the Protocol to receive data, the process that calls the Recv will receive a sigpipe signal, the process processes this signal by default.

VII. Bind Functions
Int BIND (
Socket s,
Const struct sockaddr far * Name,
Int namelen
);
After a socket is created, the data structure of the socket contains a default IP address and a default port number. A service program must call the BIND function to bind an IP address and a specific port number to it. Generally, a customer program does not need to call the BIND function to bind an IP address and a disconnected slogan to its socket. The first parameter of the function specifies the socket descriptor to be bound. The second parameter specifies a sockaddr structure, which is defined as follows:
Struct sockaddr {
U_short sa_family;
Char sa_data [14];
};
Sa_family specifies the address family. For sockets in the TCP/IP protocol family, set af_inet. When binding a socket in the TCP/IP protocol family, we usually use another address structure:
Struct sockaddr_in {
Short sin_family;
U_short sin_port;
Struct in_addr sin_addr;
Char sin_zero [8];
};
Sin_family sets AF_INET; sin_port indicates the port number. The sin_addr struct has only one unique field s_addr, indicating the IP address. This field is an integer and is generally used as the inet_addr () function () convert an IP address in string form to an integer of the unsigned long type and then set it to s_addr. Some servers are multi-host machines with at least two NICs. Therefore, when a service program running on such a server binds an IP address to its Socket, you can set htonl (INADDR_ANY) to s_addr, the advantage of this is that the client program can communicate with the service program no matter which network segment. If you only bind a fixed IP address to the Socket of the service program running on multiple hosts, then, only the client program that is in the same network segment as the IP address can communicate with the service program. We use 0 to fill the sin_zero array to make the size of the sockaddr_in structure consistent with that of the sockaddr structure. The following is an example of a bind function call:
Struct sockaddr_in saddr;
Saddr. sin_family = AF_INET;
Saddr. sin_port = htons (8888 );
Saddr. sin_addr.s_addr = htonl (INADDR_ANY );
Bind (ListenSocket, (struct sockaddr *) & saddr, sizeof (saddr ));

8. listen Functions
Int listen (SOCKET s, int backlog );
A service program can call the listen function to make its stream socket s in the listening state. The stream socket s in the listening status maintains a Client Connection Request queue, which can accommodate a maximum of backlog client connection requests. If the function is successfully executed, 0 is returned. If the function fails to be executed, SOCKET_ERROR is returned.

9. accept Function
SOCKET accept (
SOCKET s,
Struct sockaddr FAR * addr,
Int FAR * addrlen
);
The service program calls the accept function to retrieve the first client request from the client connection request queue of the stream socket s in the listening state, create a new socket to create a connection channel with the customer socket. If the connection is successful, return the descriptor of the new socket. In the future, the new socket will exchange data with the customer socket; if it fails, INVALID_SOCKET is returned. The first parameter of the function specifies the stream socket in the listening state. The operating system uses the second parameter to return the address structure of the newly created socket; 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 an accept call:
Struct sockaddr_in ServerSocketAddr;
Int addrlen;
Addrlen = sizeof (ServerSocketAddr );
ServerSocket = accept (ListenSocket, (struct sockaddr *) & ServerSocketAddr, & addrlen );

10. connect Functions
Int connect (
SOCKET s,
Const struct sockaddr FAR * name,
Int namelen
);
The customer program calls the connect function to connect the customer Socket s to the service Socket listening on the specific port of the Computer specified by name. If the connection is successful, connect returns 0; if the connection fails, SOCKET_ERROR is returned. The following is an example:
Struct sockaddr_in daddr;
Memset (void *) & daddr, 0, sizeof (daddr ));
Daddr. sin_family = AF_INET;
Daddr. sin_port = htons (8888 );
Daddr. sin_addr.s_addr = inet_addr ("133.197.22.4 ");
Connect (ClientSocket, (struct sockaddr *) & daddr, sizeof (daddr ));

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.