【问题标题】:how can i find my ip address with python not local ip?我怎样才能用python找到我的IP地址而不是本地IP?
【发布时间】:2020-08-04 10:19:22
【问题描述】:

我怎样才能用python找到我的IP地址而不是本地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)

【问题讨论】:

标签: python selenium import pip installation


【解决方案1】:

我曾经遇到过这个问题,这是我的解决方案:

然后你应该安装这个包:

import requests

...

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

print(public_ip)

无法使用socket获取公网IP

【讨论】:

    【解决方案2】:
    #! /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)
    

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 2021-08-20
      • 2013-02-14
      • 2012-10-02
      • 2021-01-03
      相关资源
      最近更新 更多