第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

python 如何獲取本地ip地址?

python 如何獲取本地ip地址?

PHP
揚(yáng)帆大魚(yú) 2023-11-09 21:09:14
我在互聯(lián)網(wǎng)上找到了一段代碼,它表示它為我的機(jī)器提供了本地網(wǎng)絡(luò) IP 地址:hostname = socket.gethostname() local_ip = socket.gethostbyname(hostname)但它返回的IP是192.168.94.2,但我在WIFI網(wǎng)絡(luò)中的IP地址實(shí)際上是192.168.1.107 我怎樣才能只用python獲取wifi網(wǎng)絡(luò)本地IP地址?我希望它適用于 Windows、Linux 和 MacOS。
查看完整描述

2 回答

?
慕無(wú)忌1623718

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊

您可以使用此代碼:


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


查看完整回答
反對(duì) 回復(fù) 2023-11-09
?
Cats萌萌

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊

您只能通過(guò)互聯(lián)網(wǎng)上的外部服務(wù)器獲知您的公共 IP 地址。有許多網(wǎng)站可以輕松提供此信息。以下是來(lái)自 Python 模塊的代碼whatismyip,可以從公共網(wǎng)站獲取它:


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然后調(diào)用whatismyip.whatismyip()。


查看完整回答
反對(duì) 回復(fù) 2023-11-09
  • 2 回答
  • 0 關(guān)注
  • 180 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)