Finding the source IP address when binding to 0.0.0.0

When binding a UDP socket to ("", 1234)or ("0.0.0.0", 1234), is it possible to find out which IP address it will actually send?

As you can see in the code below, it getsocknamejust tells me what I'm attached to. But when I send the packet, I see that the IP address is in my case 10.0.0.2.

Should I print this address myself by looking at my network interfaces? If so, this is normal, but do you have a reliable way?

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 tried to do

import socket
print(socket.gethostbyname(socket.gethostname()))

but this does not seem very reliable (in case I expected 10.0.0.2, I received 127.0.1.1).

, 0.0.0.0, . , IP- , - ? , Python?

+4
2

IP-, , . , , () .

. .

from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("", 1234))
print(s.getsockname()) # prints ("0.0.0.0", 1234)
sq = socket(AF_INET, SOCK_DGRAM)
sq.connect(("10.0.0.3", 1234))
print(sq.getsockname()[0])
sq.close()
s.sendto("hello", ("10.0.0.3", 1234)) # sends from 10.0.0.2
+2

, . , .

socket.gethostbyname_ex(socket.gethostname()). IP- . , - . IP-.

, . , NAT, VPN. , , .

@Joachim_Pileborg . .

, . , .

+1

Source: https://habr.com/ru/post/1534989/


All Articles