[Twisted-Python] Can I get the interface's IP addr from where the datagram is received?

Tommi Virtanen tv at twistedmatrix.com
Wed Jul 6 11:21:26 EDT 2005

Eric Hsu wrote:
> I'm writting a udp server which may have multiple instances listening
> on multiple network interfaces, I need to get the network interface's
> address when datagrame received:
> class MyUdpServer(DatagramProtocol):
>     def datagramReceived(self, data, addr):
>         print "The client's addr is", addr
>         print "My addr is", ???
> How can I retrieve the IP?
> Thanks in advance!

Assumption: you really need to know the address the packet was sent to,
and not just "(one of) my IP address(es)".

1) the portable, ugly way: iterate all local addresses, bind to each
separately, map socket fd -> IP address when receiving. Note that
modern OSes allow more than one address per interface. Sucks a lot
if anything changes during runtime, too.

2) the Linux-specific, nice way: see IP_PKTINFO in ip(7), recvmsg(2),
cmsg(3), etc. For python, use eunuchs.recvmsg, see

More information about the Twisted-Python mailing list