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

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

On Tue, Nov 26, 2013 at 6:35 AM, Malte Forkel <malte.forkel at> 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 "") means you use TCP/IP as normal,
but the strict word "localhost", which is normally equivalent to the
address, 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:

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

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".


More information about the Python-list mailing list