2 回答

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

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()。
- 2 回答
- 0 關注
- 164 瀏覽
添加回答
舉報