tags:

views:

51

answers:

1

How can I tell if my client system has a network connection using python? I can assume the client connected with DHCP. I can't use lists of known reliable sites to ping to test the connection, as it needs to work in isolated networks as well as open ones.

I thought about fetching the local ip (should work, so long as it doesn't only return loopback). But....

print socket.gethostbyaddr('localhost')

returns

('localhost', ['ip6-localhost', 'ip6-loopback'], ['::1'])

which isn't very useful. Any other ideas would be appreciated, thanks!

+4  A: 

localhost should always return 127.0.0.1 in ip4, '::1' in ip6, so of course it's not going to be useful -- it's the loopback interface, not the ethernet card or whatever;-).

Personally, I'd use subprocess.Popen to run ifconfig and parse the results (it's spelled ipconfig in Windows) -- not ideal, but pretty practical, IMNSHO;-).

Alex Martelli
Indeed. I suppose it would be a simple matter to search for 'inet addr:' in the response.
directedition
@direct, unfortunately depends a bit on the platform (e.g., on my Mac ifconfig says `inet 192.168.1.75` and the like, no `addr:` there), but it should be feasible to concoct either a smart-ish RE to match on various platforms, or a platform-dependent simple string check (you need to be a little platform dependent anyway to say `ifconfig` on unix and `ipconfig` on windows, after all).
Alex Martelli
use `ip` commands - ifconfig is deprecated. You could also try querying NetworkManager on Linux as a first try, then fall back on parsing the output of `ip addr`.
MikeyB
thanks mikeyb, I've gone with: while('state UP' in subprocess.Popen(['ip','addr']):
directedition