亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 164 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號