In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
Today, I will talk to you about how the Python script demonstrates the UDP and the client. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
The editor first introduces another core protocol of the transport layer, UDP, then compares the characteristics of TCP and UDP, and finally demonstrates the communication process between the UDP server and the client with the help of Python script.
0x01 UDP protocol
UDP (User Datagram Protocol, user Datagram Protocol) is a connectionless, unreliable, Datagram-based transport layer communication protocol.
Compared with TCP, the communication process of UDP is relatively simple, and it does not need complicated three-way handshake and four waves, which reflects the lack of connection.
The transmission speed of UDP is faster than that of TCP, but it is easy to lose packets, there is no guarantee of data arrival sequence, lack of congestion control, and adhering to the principle of best effort delivery, which reflects the unreliability.
The connectionless and unreliable characteristics of UDP are destined to be unable to adopt the byte flow communication mode. The Datagram-based communication mode can be reflected by "Datagram" in the protocol name and "SOCK_DGRAM" in the socket type.
In order to more intuitively compare the similarities and differences between TCP and UDP, the author organizes them into the following table:
TCPUDP connection mode connection oriented (single point communication) connectionless (multipoint communication) reliable transmission reliability communication mode based on byte flow based on Datagram header structure complex (at least 20 bytes) simple (8 bytes) slow and fast transmission resource requirements what is the order of arrival guarantee that there is no guarantee that there is no flow control, there is no congestion control, there is a small amount of data transmission supported application layer protocols Telnet, FTP, SMTP, HTTPDNS 、 DHCP 、 TFTP 、 SNMP0x02 Network Socket
Network Socket (Network socket) is the data flow endpoint of inter-process communication in computer network. In a broad sense, it also represents a mechanism of inter-process communication provided by the operating system.
The fundamental premise of interprocess communication (Inter-Process Communication,IPC) is the ability to uniquely identify each process. In the interprocess communication of the local host, PID (process ID) can be used to uniquely identify each process, but the PID is only unique locally, and the PID of different hosts in the network may conflict, so the way of "IP address + transport layer protocol + port number" is used to uniquely mark a process in the network.
Tip: the IP address of the network layer can uniquely identify the host, and the TCP/UDP protocol and port number of the transport layer can uniquely identify a process of the host. Note that the same port number can be used for TCP and UDP protocols on the same host.
All programming languages that support network communication provide a set of socket API. Take Python 3 as an example to explain the interactive process of establishing a UDP communication connection between the server and the client:
It can be seen that the communication process of UDP is much simpler than that of TCP, the server has less process of listening and accepting connection, and the client also has less process of requesting connection. The client only needs to know the address of the server and send data directly to it, and the server also opens the door to receive any data sent to its own address.
Tip: because UDP uses connectionless mode, the UDP server does not know the address of the client before it receives the data from the client, so the client must send the data first, and the server must respond to the data later. TCP is different. After accepting the connection from the client, the TCP server can not only send data to the client, but also wait for the client to send data before responding.
0x03 UDP server #! / usr/bin/env python3#-*-coding: utf-8-*-import sockets = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) s.bind (("127.0.0.1", 6000)) print ("UDP bound on port 6000...") while True: data Addr = s.recvfrom (1024) print ("Receive from% s"% addr) if data = = b "exit": s.sendto (b "Good bye!\ n", addr) continue s.sendto (b "Hello% s!\ n"% data, addr)
Line 5: create a socket object, the first parameter is socket.AF_INET, which represents the use of IPv4 protocol for network communication, and the second parameter is socket.SOCK_DGRAM, which represents the use of UDP protocol for connectionless network communication.
Line 6: bind the server host address ("127.0.0.1", 6000) to the socket object, that is, the UDP 6000 port of the local host.
Line 9: enter the cycle of data interacting with the client.
Line 10: receives data from the client, including the bytes object data, and the client's IP address and port number addr, where addr is a binary (host, port).
Line 11: prints a reception message indicating that data has been received from a client with an address of addr.
Line 12: if the bytes object is b "exit", the end response message b "Good bye!\ n" is sent to the client with the address addr. After sending, continue to wait for data from other UDP clients.
Line 15: if the bytes object is not b "exit", the greeting response message b "Hello% s!\ n" is sent to the client with the address addr, where% s is the bytes object sent by the client. After sending, continue to wait for data from any UDP client.
Compared with the TCP server, the UDP server does not need to use multithreading, because it does not need to create a separate connection for each communication process, but adopts the "receive and send" mode, which once again reflects the connectionless nature of UDP.
0x04 UDP client #! / usr/bin/env python3#-*-coding: utf-8-*-import sockets = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) addr = ("127.0.0.1", 6000) while True: data = input ("Please input your name:") if not data: continue s.sendto (data.encode (), addr) response Addr = s.recvfrom (1024) print (response.decode ()) if data = "exit": print ("Session is over from the server% Spura% s\ n"% addr) breaks.close ()
Line 5: create a socket object, the first parameter is socket.AF_INET, which represents the use of IPv4 protocol for network communication, and the second parameter is socket.SOCK_DGRAM, which represents the use of UDP protocol for connectionless network communication.
Line 6: the address of the initialized UDP server ("127.0.0.1", 6000), that is, the UDP 6000 port of the local host.
Line 8: enter the cycle of data interacting with the server.
Line 9: the user is required to enter a name.
Line 10: when the user's input is empty, the loop is restarted, requiring the user to re-enter.
Line 12: when the user's input is not empty, the string is converted into a bytes object and sent to the UDP server with the address ("127.0.0.1", 6000).
Line 13: receives the response data of the server, including the bytes object response, as well as the server's IP address and port number addr, where addr is a binary (host, port).
Line 14: converts the response bytes object response to a string and prints it out.
Line 15: when the user's input is "exit", the session end message is printed, the cycle of data interaction with the server is terminated, and the socket is about to be closed.
Line 19: close the socket and no longer send data to the server.
0x05 UDP interprocess communication
The scripts of the UDP server and client are named udp_server.py and udp_client.py respectively, and then saved to the desktop. The author will demonstrate it with PowerShell under the Windows 10 system.
Tip: when readers replay, make sure that Python 3 is installed on this machine, and note that the author has changed the default startup path name python to python3.
Single server VS multi-client
Run the command python3. / udp_server.py in one of the PowerShell, the server binds the UDP 6000 port of the local host, and prints the message UDP bound on port 6000., waiting for the client to send data.
Run the command python3. / udp_client.py in the other two PowerShell, and send the strings Client1 and Client2 to the server
The server prints the receiving information, indicating that the data is received from UDP ports 63643 and 63644 respectively, and sends the greeting response information to the client respectively.
If the client Client1 sends an empty string, it is required to re-enter
The client Client2 first sends the string Alice to get the greeting response information of the server, then sends the string exit to get the end response information of the server, and finally prints the session end information to terminate the data exchange with the server.
The client Client1 sends the string exit, gets the end response information of the server, prints the session end information, and terminates the data exchange with the server.
The server prints and receives the information according to the data sending order of the above client, and continues to wait for any UDP client to send data.
0x06 Python API Referencesocket module
This section introduces the built-in module socket used in the above code, which is the core module of Python network programming.
Socket () function
The socket () function is used to create a socket object in network communication. The function prototype is as follows:
Socket.socket (family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
The family parameter represents the address family (Address Family), and the default value is AF_INET, which is used for IPv4 network communications and, most commonly, AF_INET6, for IPv6 network communications. The optional value of the family parameter depends on the native operating system.
The type parameter represents the type of socket, and the default value is SOCK_STREAM, which is used for TCP protocol (connection-oriented) network communication, and commonly used SOCK_DGRAM, for UDP protocol (connectionless) network communication.
The proto parameter represents the protocol of the socket, and the default value is 0, which is generally ignored. Unless the family parameter is AF_CAN, the proto parameter should be set to CAN_RAW or CAN_BCM.
The fileno parameter represents the socket's file descriptor, and the default value is None. If this parameter is set, the other three parameters will be ignored.
After creating the socket object, you need to use the built-in function of the object to complete the network communication process. Note that the "socket" in the following function prototype refers to the socket object, not the socket module above.
Bind () function
The bind () function is used to bind an IP address and port number to a socket object. Note that the socket object must not be bound and the port number is not occupied, otherwise an error will be reported. The function prototype is as follows:
Socket.bind (address)
The address parameter represents the address to which the socket is bound, and its format depends on the socket's family parameter. If the family parameter is AF_INET, the address parameter is represented as a binary (host, port), where host is the host address represented by a string and port is the port number represented by integers.
Sendto () function
The sendto () function is used to send data to a remote socket object. Note that this function is used for connectionless communication between UDP processes, and the address of the remote socket is specified in the parameters, so you do not need to connect to the remote socket before using it. In contrast, connection-oriented communication between TCP processes requires the send () function. The function prototype is as follows:
Socket.sendto (bytes [, flags], address)
The bytes parameter represents the bytes object data to be sent. For example, for the string "hello world!" As far as it is concerned, you need to convert the encode () function to the bytes object b "hello world!" In order to carry out network transmission.
The flags optional parameter is used to set the special function of the sendto () function. The default value is 0, or it can be composed of one or more predefined values, separated by bits or operators. For details, please refer to sendto (2) in the Unix function manual. The common values of flags parameters are MSG_OOB, MSG_EOR, MSG_DONTROUTE and so on.
The address parameter represents the address of the remote socket, and its format depends on the socket's family parameter. If the family parameter is AF_INET, the address parameter is represented as a binary (host, port), where host is the host address represented by a string and port is the port number represented by integers.
The return value of the sendto () function is the number of bytes of data sent.
Recvfrom () function
The recvfrom () function is used to receive data from a remote socket object. Note that unlike the sendto () function, the recvfrom () function can be used for both UDP and TCP inter-process communication. The function prototype is as follows:
Socket.recvfrom (bufsize [, flags])
The bufsize parameter represents the maximum number of bytes that a socket can receive data. Note that in order for the hardware device to better match the network transport, the value of the bufsize parameter is best set to the power of 2, for example, 4096.
The flags optional parameter is used to set the special function of the recv () function. The default value is 0, or it can be composed of one or more predefined values, separated by bits or operators. For details, please refer to recvfrom (2) in the Unix function manual. The common values of flags parameters are MSG_OOB, MSG_PEEK, MSG_WAITALL and so on.
The return value of the recvfrom () function is a binary (bytes, address), where bytes is the received bytes object data, and address is the sender's IP address and port number, represented by a binary (host, port). Note that the return value of the recv () function is only bytes object data.
Close () function
The close () function closes the local socket object and releases all resources connected to the socket.
Socket.close () after reading the above, do you have any further understanding of how the Python script demonstrates the UDP and the client? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.