How can I get the IP address from NIC in Python?
Two methods:
Method #1 (use external package)
You need to ask for the IP address that is bound to your eth0
interface. This is available from the netifaces package
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print(ip) # should print "192.168.100.37"
You can also get a list of all available interfaces via
ni.interfaces()
Method #2 (no external package)
Here's a way to get the IP address without using a python package:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0') # '192.168.0.110'
Note: detecting the IP address to determine what environment you are using is quite a hack. Almost all frameworks provide a very simple way to set/modify an environment variable to indicate the current environment. Try and take a look at your documentation for this. It should be as simple as doing
if app.config['ENV'] == 'production':
#send production email
else:
#send development email
Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:
import socket
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.
A simple approach which returns a string with IP addresses for the interfaces is:
from subprocess import check_output
ips = check_output(['hostname', '--all-ip-addresses'])
For more information, see hostname.