When binding a UDP socket to ("", 1234)
or ("0.0.0.0", 1234)
, is it possible to find out what IP-address it will actually send from?
As you can see in the code below, getsockname
only tells me what I bound to. But when I send a packet, I can see that the IP-address is, in my case, 10.0.0.2
.
Do I have to infer this address myself by looking at my network interfaces? If so, that is fine, but is there a robust way of doing so?
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("", 1234))
print(s.getsockname()) # prints ("0.0.0.0", 1234)
s.sendto("hello", ("10.0.0.3", 1234)) # sends from 10.0.0.2
I've tried doing
import socket
print(socket.gethostbyname(socket.gethostname()))
but that doesn't seem to be very reliable (in the case where I expected 10.0.0.2
, I got 127.0.1.1
).
I realize that by binding to 0.0.0.0
, I bind to all local network interfaces. Does that mean that my source IP-address will be determined by the routing tables when I try to send something? If so, can I still get that address in a robust way from Python?