If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Friday, July 10, 2009

What's My IP?

#!/usr/bin/env python
'''Find local machine IP (cross platform)'''

from subprocess import Popen, PIPE
from sys import platform
import re

COMMANDS = {
"darwin" : "/sbin/ifconfig",
"linux" : "/sbin/ifconfig",
"linux2" : "/sbin/ifconfig",
"win32" : "ipconfig",
}

def my_ip():
command = COMMANDS.get(platform, "")
assert command, "don't know how to get IP for current platform"

pipe = Popen([command], stdout=PIPE)
pipe.wait()
output = pipe.stdout.read()

for ip in re.findall("(\d+\.\d+\.\d+\.\d+)", output):
if ip.startswith("127.0.0"):
continue
return ip

if __name__ == "__main__":
print my_ip()

2 comments:

lorg said...

I guess it's probably good enough for you, but discovering your own IP isn't really that simple in the general case:

1. If you are behind a NAT, and you want to find your outside address, this won't work. (That's why there are websites like whatismyip.com)

2. If your station is using IPv6. I never got to program for it myself, but I guess one of these days we'll have to start :)

3. In win32, ipconfig might return results that will confuse your script. Consider the case of an interface that doesn't have an IP address defined, but does have a subnet mask defined, or a default gateway.

Bottom line: be weary of too easy solutions :)

Miki Tebeka said...

It works for me in the current settings :)

A more reliable one will be to do something like:

from socket import (socket,
AF_INET, SOCK_STREAM)
s = socket(AF_INTET, SOCK_STREAM)
s.connect(("google.com", 80))
ip = s.getsockname()[0]


However I wanted something that does run a network connection.

Blog Archive