为了账号安全,请及时绑定邮箱和手机立即绑定

python 如何获取本地ip地址?

python 如何获取本地ip地址?

PHP
扬帆大鱼 2023-11-09 21:09:14
我在互联网上找到了一段代码,它表示它为我的机器提供了本地网络 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。
查看完整描述

2 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您可以使用此代码:


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"])


查看完整回答
反对 回复 2023-11-09
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

您只能通过互联网上的外部服务器获知您的公共 IP 地址。有许多网站可以轻松提供此信息。以下是来自 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()。


查看完整回答
反对 回复 2023-11-09
  • 2 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信