Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Server and client based on UDP

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

In the following article, we give several examples of TCP, as far as UDP is concerned, you only need to understand the following content, complete and censure things.

There is no connection between server and client in UDP.

Unlike TCP, UDP does not need to exchange data in a cohesive mode, so UDP-based servers and clients do not need to go through the cohesive process. That is, you don't have to misappropriate the listen () and accept () functions. In UDP, only the process of creating sockets and the process of data exchange are needed.

Only one socket is required for both the UDP server and the client

In TCP, sockets are one-to-one relationships. If you want to provide services to 10 clients, you need to create 10 sockets in addition to the listening sockets. However, in UDP, both the server side and the client side require only one socket. The example of mailing parcels was given when explaining the truth of UDP. The express company that mailed parcels can, for example, use UDP sockets, through which parcels can be mailed to arbitrary addresses through only one express company. Similarly, only one UDP socket is needed to transmit data to arbitrary hosts.

Accept and send function based on UDP

After the creation of TCP sockets, there is no need to add address information when transmitting data, because TCP sockets will adhere to the connection with each other's sockets. In other words, the TCP socket knows the destination address information. However, UDP sockets do not adhere to the cohesive form, and the destination address information is added every time the data is transmitted, which is equivalent to filling in the recipient's address before mailing the package.

Send data using the sendto () function:

Ssize_t sendto (int sock, void * buf, size_t nbytes, int flags, struct sockaddr * to, socklen_t addrlen); / Linux int sendto (SOCKET sock, const char * buf, int nbytes, int flags, const struct sockadr * to, int addrlen); / / Windows

The sendto () function under Linux and Windows is similar. Here are the specific parameters:

Sock: a socket used to transmit UDP data

Buf: the buffer address that holds the data to be transferred

Nbytes: length of data with transmission (in bytes)

Flags: optional parameter, if no 0 can be passed

To: the address of the sockaddr constructor variable containing the destination address information

Addrlen: the length of the address value constructor variable passed to the parameter to.

The biggest difference between the UDP sending function sendto () and the TCP sending function write () / send () is that the sendto () function needs to pass him the destination address information.

To accept data, use the recvfrom () function:

Ssize_t recvfrom (int sock, void * buf, size_t nbytes, int flags, struct sockadr * from, socklen_t * addrlen); / / Linux int recvfrom (SOCKET sock, char * buf, int nbytes, int flags, const struct sockaddr * from, int * addrlen); / / Windows

Because the sender of UDP data is uncertain, the recvfrom () function is defined as a way to accept information from the sender. The detailed parameters are as follows:

Sock: a socket used to accept UDP data

Buf: the address of the buffer that holds the accepted data

Nbytes: maximum number of bytes that can be accepted (cannot exceed the size of the buf buffer)

Flags: optional parameter, if no 0 can be passed

From: the address of the sockaddr constructor variable that contains the sender address information

Addrlen: holds the variable address value of the constructor variable length of the parameter from.

Response server end / client based on UDP

The following is to combine the previous content to complete the response client. It is important to note that UDP differs from TCP, and there is no process of pleading for convergence and acceptance, so in a sense it is impossible to distinguish between the server side and the client side, but it is called the server side because of its supply service.

The code under Windows is given below, and Linux is similar to this, so I won't repeat it.

Server server.cpp:

# include # include # pragma comment (lib, "ws2_32.lib") / / load ws2_32.dll # define BUF_SIZE 100 int main () {WSADATA wsaData; WSAStartup (MAKEWORD (2,2), & wsaData); / / create socket SOCKET sock = socket (AF_INET, SOCK_DGRAM, 0); / / bind socket sockaddr_in servAddr; memset (& servAddr, 0, sizeof (servAddr)); / / populate servAddr.sin_family = PF_INET with 0 in each byte / / use IPv4 address servAddr.sin_addr.s_addr = htonl (INADDR_ANY); / / actively obtain IP address servAddr.sin_port = htons (1234); / / Port bind (sock, (SOCKADDR*) & servAddr, sizeof (SOCKADDR)); / / accept client request SOCKADDR clntAddr; / / client address information int nSize = sizeof (SOCKADDR); char buffer [BUF _ SIZE] / / buffer while (1) {int strLen = recvfrom (sock, buffer, BUF_SIZE, 0, & clntAddr, & nSize); sendto (sock, buffer, strLen, 0, & clntAddr, nSize);} closesocket (sock); WSACleanup (); return 0;}

The code clarifies:

1) Line 12, when creating the socket, passes SOCK_DGRAM to the second parameter socket () to indicate the use of the UDP protocol.

2) in line 18, htonl (INADDR_ANY) is used to actively obtain the IP address.

Using the constant INADDR_ANY to actively obtain the IP address has a clear benefit, that is, when the software device changes to another server or server IP address, there is no need to change the source code to recompile or manually output the software when starting the software. And if multiple IP addresses (such as routers) have been assigned to a computer, data can be accepted from different IP addresses as long as the end slogan diverges. Therefore, priority is given to the use of INADDR_ANY; in the server and will not be taken in the client unless there is a local server function.

Client client.cpp:

# include # include # pragma comment (lib, "ws2_32.lib") / / load ws2_32.dll # define BUF_SIZE 100 int main () {/ / initialize DLL WSADATA wsaData; WSAStartup (MAKEWORD (2,2), & wsaData); / / create socket SOCKET sock = socket (PF_INET, SOCK_DGRAM, 0); / / Server address information sockaddr_in servAddr; memset (& servAddr, 0, sizeof (servAddr)) / / fill every byte with 0 servAddr.sin_family = PF_INET; servAddr.sin_addr.s_addr = inet_addr ("127.0.0.1"); servAddr.sin_port = htons (1234); / / take the user output from time to time and send it to the server, and then accept the server data sockaddr fromAddr; int addrLen = sizeof (fromAddr); while (1) {char buffer [BUF _ SIZE] = {0}; printf ("Input a string:"); gets (buffer) Sendto (sock, buffer, strlen (buffer), 0, (struct sockaddr*) & servAddr, sizeof (servAddr)); int strLen = recvfrom (sock, buffer, BUF_SIZE, 0, & fromAddr, & addrLen); buffer [strLen] = 0; printf ("Message form server:% s\ n", buffer);} closesocket (sock); WSACleanup (); return 0;}

Run server first, and then run client,client input result as follows:

Input a string: C language Chinese website

Message form server: C language Chinese website

Input a string: c.biancheng.net Founded in 2012

Message form server: c.biancheng.net Founded in 2012

Input a string:

As can be seen from the code, the listen () function is not used in server.cpp, and the connect () function is not used in client.cpp, because UDP does not require convergence.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report