Paul Clarke
Paul Clarke

Reputation: 338

Send using UDP between 2 local computers without knowing IP addresses using Python3

I'm trying to develop an app to send a json string from one computer on the wireless network to another (or a phone). The problem is it has to work without knowing the IP address of the recieving computer.

The below code works if i know the IP address to send to

# UDP Server
import socket

IP = "123.123.123.123" # Not actual IP address
PORT = 66666

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((IP,PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print(f"recieved message: {data} from: {addr}")


# UDP Client
import socket

IP = "123.123.123.123" # Not actual IP address
PORT = 66666

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

MSG = b"Hello there"

sock.sendto(MSG, (IP, PORT))

I can also use sock.getsockname()[0] to get the current IP address and listen to it, but what about sending?

I've read a few tutorials and some say to use 0.0.0.0 to send or listen to all addresses however nothing is recieved with this. The other idea was to use 192.0.0.1 on both ends to listen and send to the router but then I get 'OSError: [WinError 10049] The requested address is not valid in its context'

I thought about using broadcast but have read that this is very bad practice to the point where it was used from ipv6.

I read a suggestion to use multicasting but is there a way to get all IP addresses of computers on the local network in order to use this?

Any assistance would be hugely appreciated!

Upvotes: 0

Views: 1069

Answers (1)

Paul Clarke
Paul Clarke

Reputation: 338

Thanks to help from rdas referring me to https://gist.github.com/ninedraft/7c47282f8b53ac015c1e326fffb664b5 i've managed to solve the issue with the below;

# UDP Server
import socket

PORT = 66666

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROT_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.bind(("",PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print(f"recieved message: {data} from: {addr}")


# UDP Client
import socket

PORT = 66666

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROT_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

MSG = b"Hello there"

sock.sendto(MSG, ('<broadcast>', PORT))

Upvotes: 1

Related Questions