首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python而不是本地ip来查找我的ip地址?

问如何使用python而不是本地ip来查找我的ip地址?
EN

Stack Overflow用户
提问于 2020-04-21 23:41:11
回答 2查看 1.2K关注 0票数 1

如何使用python而不是本地ip来查找我的ip地址?我尝试使用套接字,但它找到本地ip。我需要通过以太网连接外部ip。这是我代码,但它找到本地ip

代码语言:javascript
复制
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
EN

回答 2

Stack Overflow用户

发布于 2020-04-22 00:03:23

我曾经有过这样的问题,我的解决方案是:

你应该安装这个包,然后:

代码语言:javascript
复制
import requests

...

public_ip = requests.get("http://wtfismyip.com/text").text

print(public_ip)

无法使用socket获取公网IP

票数 3
EN

Stack Overflow用户

发布于 2020-04-21 23:54:44

代码语言:javascript
复制
#! /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)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61347442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档