How to determine whether client and server are on the same host

Chris Angelico rosuav at gmail.com
Tue Nov 26 00:07:37 CET 2013


On Tue, Nov 26, 2013 at 6:35 AM, Malte Forkel <malte.forkel at berlin.de> wrote:
> I have a Python application that communicates with a server via telnet.
> Host and port of the server are supplied by the user when the
> application is started.
>
> How can I determine from within the application whether the server's
> host actually is the local host? (In that case I could implement an
> operation not available in the telnet-based protocol by directly
> accessing the local filesystem.)

Two easy ways you could do this. I would be inclined to do what
PostgreSQL and others do, and have an explicit indication that you
want to use a local method: for instance, the name "localhost". Use of
anything else (including "127.0.0.1") means you use TCP/IP as normal,
but the strict word "localhost", which is normally equivalent to the
address 127.0.0.1, would signal your app to use the direct method (for
PostgreSQL, that's a Unix socket rather than a TCP one). This means
you can still force telnet to be used even if you're working locally -
good for debugging.

Alternatively, you can simply query the current network interfaces for
their IPs, and see if the IP you were given is in that list. I don't
know of a way to do that in core Python, but the C function you need
is getifaddrs(), and this claims to wrap all that up nicely:

https://pypi.python.org/pypi/netifaces

This method would detect, for instance, that calling up 192.168.0.19
port 12345 is a local lookup, because eth0 has address 192.168.0.19,
and that 192.168.2.2 port 54321 is local too, because wlan0 has
address 192.168.2.2.

If you aren't too concerned with running this on multiple platforms
(which seems likely - working with the local filesystem implies you
know a lot about what the server and client are doing), you could
simply parse the output of 'ip addr', 'ipconfig', 'ifconfig', or some
equivalent network utility for your platform. That might be easier
than playing with the package, depending on environment. But it'd be
even simpler - and in some ways better - to be explicit about "use a
direct connection rather than TCP".

ChrisA



More information about the Python-list mailing list