SoFunction
Updated on 2024-11-21

Python implementation of UDP program communication process illustration

Running process: After editing the code, open the file through cmd to execute. Example: C:\Users\Bruce Lee Jr. (1960-), US actor and pop singer>C:\Users\Bruce Lee Jr. (1960-), US actor and pop singer\Desktop\transmitter.py hello

Easy to see problem: When running the program, it is easy to get "invalid request address":

This is because the ip address entered while editing the code was incorrect.

Solution:

Open cmd and type ipconfig to view the local ip address. As shown in the figure below

After that, just change it to the correct IP address in the code line.

1. Code

(1) Receiving end code:

import socket
# Use the IPV4 protocol to transfer data using the UDP protocol
s=(socket.AF_INET, socket.SOCK_DGRAM)
#Bind port and port number, empty string indicates any available IP address on the local machine
(('192.168.0.106', 5000))
while True:
  data, addr=(1024)
   # Display received content
  print('received message:{0} from PORT {1} on {2}'.format((),
                               addr[1], addr[0]))
  if ().lower() == 'bye':
    break
( )

(2) Transmitter code:

import socket
import sys
s=(socket.AF_INET, socket.SOCK_DGRAM)
([1].encode() , ("192.168.0.106" ,5000))# Assume 192.168.0.103 is the IP address of the receiving machine
( )

2. Running results:

(1) Transmitter:

(2) Receiving end:

This is the whole content of this article.