python 如何获取运行 web 应用程序的计算机的 ip 地址

How to get the ip address of the computer which runs a web application in python

我正在开发 Web API 我想获取使用我的应用程序的计算机的 IP 地址。我使用 python 开发了我的 API。并且用户可能正在使用任何 os.

我使用此代码获取 IP 地址,但这并没有在每个平台上给出正确的结果。

socket.gethostbyname(gethostname())

我建议使用 netifaces 库:https://pypi.python.org/pypi/netifaces 否则很难跨平台兼容。

文档中的示例:

>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']


>>> netifaces.ifaddresses('lo0')
{18: [{'addr': ''}], 2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}], 30: [{'peer': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'addr': '::1'}, {'peer': '', 'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::1%lo0'}]}