Python - Get localhost IP [duplicate]

随声附和 提交于 2019-12-17 18:55:39

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11735821/python-get-localhost-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!