简体   繁体   English

如何获取本地IP地址python?

[英]How to get local ip address python?

There's a code I found in internet that says it gives my machines local network IP address:我在互联网上找到了一个代码,上面写着它为我的机器提供了本地网络 IP 地址:

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

but the IP it returns is 192.168.94.2 but my IP address in WIFI network is actually 192.168.1.107 How can I only get wifi network local IP address with only python?但它返回的 IP 是 192.168.94.2 但我在 WIFI 网络中的 IP 地址实际上是 192.168.1.107 我怎样才能只用 python 获取 wifi 网络本地 IP 地址? I want it to work for windows,linux and macos.我希望它适用于 windows、linux 和 macos。

You can use this code:您可以使用以下代码:

import socket
hostname = socket.getfqdn()
print("IP Address:",socket.gethostbyname_ex(hostname)[2][1])

or this to get public ip:或者这个来获得公共IP:

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

Here's code from the whatismyip Python module that can grab it from public websites:以下是whatismyip Python 模块的代码,可以从公共网站获取它:

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())

Or you can install pip install whatismyip and then call whatismyip.whatismyip() .或者你可以安装pip install whatismyip然后调用whatismyip.whatismyip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM