Let`s learn how to send some data to the local network and receive the same data as the recipient on the same machine to demonstrate the use of a datagram.
To find out the IP configuration of your computer, use this command on the terminal:
Code # 1: For the end of the sender.
" localhost "
" message: "
socket.socket (socket.AF_INET, socket.SOCK_DGRAM) p >
sock.sendto (bytes (MESSAGE,
) , (UDP_IP, UDP_PORT))
- Please enter your IPv4 address instead of UDP_IP and remember that port number 8080 — this is the port number of your localhost, so you need to specify it.
socket.socket () uses your system`s IPv4 address, and SOCK_DGRAM — this is the type of protocol we use for communication.
- Use the sock object to call the
sendto () function, then pass the tuple argument containing the IP address and port number.
Step # 2: at the receiver end.
socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
sock.bind (( UDP _IP, UDP_PORT))
Received Message: b`Geeksforgeeks`
- We need to specify the localhost IP in
UDP_IP and use the socket.socket () function, as described above. li>
- bind the parameter to a socket object so that whatever is received with that port address we intercept at that end. In a loop, define the buffer size as 1024. Since the message is small, the buffer size is sufficient.