Как я могу найти свой IP-адрес с python не локальный IP? - PullRequest
0 голосов
/ 21 апреля 2020

Как я могу найти свой IP-адрес с python не локальным IP-адресом? Я пытаюсь с сокетом, но он находит локальный IP. Мне нужно ethe rnet внешний IP. Это мой код, но он находит локальный IP

import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

Раньше у меня была эта проблема, и это было мое решение:

Вы должны установить этот пакет тогда:

import requests

...

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

print(public_ip)

Невозможно получить IP-адрес publi c, используя сокет

0 голосов
/ 21 апреля 2020
#! /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)
...