如何使用Python获取本地IP地址?

5

我在网上找到了一段代码,它可以给出我的机器的本地网络IP地址:

hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)

但是它返回的IP地址是192.168.94.2,而我的WIFI网络IP地址实际上是192.168.1.107。我该如何只使用Python获取wifi网络本地IP地址?我希望它能在Windows、Linux和macOS上正常工作。


这个回答解决了你的问题吗?使用Python标准库查找本地IP地址 - Alexandru Dinu
不,实际上我也尝试过,但它也给了我错误的IP地址。 - soroushamdg
2个回答

9
您可以使用以下代码:
import socket
hostname = socket.getfqdn()
print("IP Address:",socket.gethostbyname_ex(hostname)[2][1])

获取公网IP地址的方法:

import requests
import json
print(json.loads(requests.get("https://ip.seeip.org/jsonip?").text)["ip"])

2
这个可以工作。谢谢。 - bihari_gamer
3
将最后一个索引从1修改为0,以适应我的设置:socket.gethostbyname_ex(hostname)[2][0] - Rod Maniego

1
这是来自于 Python 模块 whatismyip 的代码,可以从公共网站获取它:
import urllib.request

IP_WEBSITES = (
           'https://ipinfo.io/ip',
           'https://ipecho.net/plain',
           'https://api.ipify.org',
           'https://ipaddr.site',
           'https://icanhazip.com',
           'https://ident.me',
           'https://curlmyip.net',
           )

def getIp():
    for ipWebsite in IP_WEBSITES:
        try:
            response = urllib.request.urlopen(ipWebsite)

            charsets = response.info().get_charsets()
            if len(charsets) == 0 or charsets[0] is None:
                charset = 'utf-8'  # Use utf-8 by default
            else:
                charset = charsets[0]

            userIp = response.read().decode(charset).strip()

            return userIp
        except:
            pass  # Network error, just continue on to next website.

    # Either all of the websites are down or returned invalid response
    # (unlikely) or you are disconnected from the internet.
    return None

print(getIp())

或者您可以安装 pip install whatismyip 然后调用 whatismyip.whatismyip()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接