[英]how can i find my ip address with python not local ip?
我怎樣才能找到我的 ip 地址與 python 不是本地 ip? 我嘗試使用套接字,但它找到本地 ip。我需要連接外部 ip。這是我的代碼,但它找到本地 ip
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
我曾經遇到過這個問題,這是我的解決方案:
你應該安裝這個 package 然后:
import requests
...
public_ip = requests.get("http://wtfismyip.com/text").text
print(public_ip)
無法使用套接字獲取公共 IP
#! /usr/bin/env python3
# Script for hourly logging own external IP address
# 2017 Octobar 21
import re
import html
import codecs
import datetime
import time
import requests
import os
time.sleep(10)
url = 'https://whatismyipaddress.com/'
dir_in = '/data/Scrape/iplog/'
assert os.path.exists(dir_in), "directory have to be created"
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17',
'From': 'josifoski@gmail.com' # This is another valid field
}
while True:
response = requests.get(url, headers=headers)
s = html.unescape(response.content.decode('utf-8'))
#with codecs.open('abc.txt', 'w') as f:
# f.write(s)
try:
ip = re.search(r'//whatismyipaddress.com/ip/(.*?)"', s).group(1)
log = codecs.open(dir_in + 'ip.log', 'a', 'utf-8')
now = str(datetime.datetime.now())[:16]
log.write(now + ' ' + ip + os.linesep)
log.close()
except:
pass
time.sleep(3600)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.