Python在Linux上获取网卡IP地址

通过Python自带的socket包提取本机IP地址的代码,在Windows上正常,但在Linux上得到的是127.0.1.1。可以通过netifaces包等方法解决。

Python在Linux上获取网卡IP地址

1 问题描述

通过Python自带的socket包提取本机IP地址的代码,如下:

1
2
import socket
socket.gethostbyname(socket.gethostname())

这段代码在Windows上正常,但在Linux上得到的是127.0.1.1

2 解决方法

我通过netifaces包解决该问题:

1
2
3
4
5
6
7
8
9
10
os_platform = platform.platform().lower()
if 'windows' in os_platform:
# get host ip
self.ip = socket.gethostbyname(self.hostname)
elif 'linux' in os_platform:
try:
if_addresses = ni.ifaddresses('eth0')
except ValueError:
if_addresses = ni.ifaddresses('eno1')
self.ip = if_addresses[ni.AF_INET][0]['addr']
  • 可以通过import platform来调取当前系统版本;
  • 大多数Linux机器外网IP的网卡都是eth0,此处eno1是根据遇到的特例加上的处理。(最好通过弄配置文件解决哈,这样多少有点hard code了)

3 参考资料

How can I get the IP address from NIC in Python? - StackOverflow

Answer: https://stackoverflow.com/a/24196955

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

1
2
3
4
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

1
ni.interfaces()

Method #2 (no external package)

Here's a way to get the IP address without using a python package:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
if app.config['ENV'] == 'production':
#send production email
else:
#send development email