[英]how can i find my ip address with python not local ip?
How can i find my ip address with python not local ip?我怎样才能找到我的 ip 地址与 python 不是本地 ip? I try with socket but it find local ip.I need to ethernet outer ip.That's my code but it find local 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)
I used to have this problem and this was my solution:我曾经遇到过这个问题,这是我的解决方案:
you should install this package then:你应该安装这个 package 然后:
import requests
...
public_ip = requests.get("http://wtfismyip.com/text").text
print(public_ip)
It's not possible to get the public IP using socket无法使用套接字获取公共 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.