Python-获取本地主机IP [英] Python - Get localhost IP

查看:80
本文介绍了Python-获取本地主机IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用Python的stdlib查找本地IP地址

要获取我的本地主机IP地址,请执行socket.gethostbyname(socket.gethostname()).但这给了我答案127.0.0.1. 如果我执行an_existing_socket.getsockname()[0],我会得到答案0.0.0.0.

我需要我的真实" IP地址(例如192.168.x.x)来修改配置文件.我怎么能得到它?

解决方案

我通常使用以下代码:

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

我不知道它的起源,但是它可以在Linux/Windows上运行.

此代码由使用 > stackoverflow问题中的smerlin . >

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?

解决方案

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.

这篇关于Python-获取本地主机IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆