[英]How do I get the external IP of a socket in Python?
當我在套接字 object 上調用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()
您需要使用外部系統來執行此操作。
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)
導入套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("msn.com",80))
s.getsockname()
print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())
使用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")
獲取公共 IP 的最簡單方法是使用此
import requests
IP = requests.get('https://api.ipify.org/').text
print(f'Your IP is: {IP}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.