Possible Duplicate:
Finding local IP addresses using Python's stdlib
To get my localhost IP address I do socket.gethostbyname(socket.gethostname())
. But it gives me the answer 127.0.0.1
.
If I do an_existing_socket.getsockname()[0]
I get the answer 0.0.0.0
.
I need my 'real' ip address (for instance 192.168.x.x) to modify a configuration file. How could I get it?
To get the public IP address of your computer, you can use the Python socket module gethostbyname() function. You can also use gethostbyname() to get the IP address of a website.
I generally use this code:
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
I don't know it's origin, but it works on Linux/Windows.
Edit:
This code is used by smerlin in this stackoverflow question.
There is a nifty module you can use. Its called netifaces. Just do a pip install netifaces into a virtualenv for testing and try the following code:
import netifaces
interfaces = netifaces.interfaces()
for i in interfaces:
if i == 'lo':
continue
iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
print j['addr']
It all depends on your environment. If you only have one interface with one IP address attached to it, you can simply do:
netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
If you are behind a NAT and want to know your public IP address, you can use something like:
import urllib2
ret = urllib2.urlopen('https://icanhazip.com/')
print ret.read()
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With