문제

내가 전화할 때 socket.getsockname() 소켓 개체에서는 내 컴퓨터의 내부 IP와 포트의 튜플을 반환합니다.하지만 외부 IP를 검색하고 싶습니다.이 작업을 수행하는 가장 저렴하고 효율적인 방법은 무엇입니까?

도움이 되었습니까?

해결책

이는 외부 서버의 협력 없이는 불가능합니다. 사용자와 다른 컴퓨터 사이에 NAT가 얼마든지 있을 수 있기 때문입니다.사용자 정의 프로토콜인 경우 다른 시스템에 연결된 주소를 보고하도록 요청할 수 있습니다.

다른 팁

내가 생각할 수 있는 유일한 방법은 당신에게 그것을 보장하는 것입니다. http://whatismyip.com/ 그것을 얻기 위해.

https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py

'''
Finds your external IP address
'''

import urllib
import re

def get_ip():
    group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
    return group['ip']

if __name__ == '__main__':
    print get_ip()

수입 소켓

s = 소켓.소켓(socket.AF_INET, 소켓.SOCK_STREAM)

s.connect(("msn.com",80))

s.getsockname()

print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())

이 작업을 수행하려면 외부 시스템을 사용해야 합니다.

DuckDuckGo의 IP 답변은 귀하가 원하는 것을 정확하게 JSON으로 제공합니다!

import requests

def detect_public_ip():
    try:
        # Use a get request for api.duckduckgo.com
        raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
        # load the request as json, look for Answer.
        # split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
        answer = raw.json()["Answer"].split()[4]
    # if there are any connection issues, error out
    except Exception as e:
        return 'Error: {0}'.format(e)
    # otherwise, return answer
    else:
        return answer

public_ip = detect_public_ip()
print(public_ip)

출처에 제시된 주소 사용 http://whatismyip.com

import urllib
def get_my_ip_address():
    whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
    return urllib.urlopen(whatismyip).readlines()[0]

외부 서버에 연결하고 응답에서 공용 IP를 가져와야 합니다.


이와 같이:

   import requests

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

   print("\n[+] My Public IP: "+ myPublic_IP+"\n")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top