Python でソケットの外部 IP を取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/58294

  •  09-06-2019
  •  | 
  •  

質問

電話すると 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 = ソケット.ソケット(ソケット.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