【问题标题】:How do I get the external IP of a socket in Python?如何在 Python 中获取套接字的外部 IP?
【发布时间】:2008-09-12 04:21:51
【问题描述】:

当我在套接字对象上调用socket.getsockname() 时,它会返回我机器的内部IP 和端口的元组。但是,我想检索我的外部 IP。这样做最便宜、最有效的方式是什么?

【问题讨论】:

  • 另一个提供简洁解决方案的优秀网站是从icanhazip.com获取HTTP请求

标签: python sockets


【解决方案1】:

如果没有外部服务器的合作,这是不可能的,因为您和另一台计算机之间可能存在任意数量的 NAT。如果是自定义协议,您可以要求其他系统报告它连接到的地址。

【讨论】:

    【解决方案2】:

    我能想到的唯一能保证给你的方法是点击http://whatismyip.com/ 之类的服务来获取它。

    【讨论】:

    • 不太清楚为什么这被否决了。恕我直言,这是获取任何系统的外部 IP 地址的唯一方法。仅仅因为路由器告诉你它认为你的 IP 地址是什么,或者它认为它的 IP 地址是什么,并不意味着没有另一个 NAT。
    • @MatthewSchinckel:+1 用于提及另一个 NAT。此外,不同的外部服务可能会看到不同的外部 IP,例如,我记得要访问图书馆站点,我必须使用不同的路由,以便站点看到不同的(允许的)IP,即公共 IP 可能取决于目的地。跨度>
    【解决方案3】:

    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()
    

    【讨论】:

    • 不知道 jsonip.com--谢谢。这是您答案的更多“jsonic”变体(自动格式化会弄乱url): json.loads(urllib2.urlopen(urllib2.Request('jsonip.com', headers = {'Content-Type': 'application /json'})).read())['ip']
    • @Rafael Lopes 链接已移至 https://jsonip.com/(永久为 301)。顺便提一句。对我来说,它完美无缺。就我而言,响应中的外部 IP 是 IPv6 格式,这很好。不错。
    【解决方案4】:

    您需要使用外部系统来执行此操作。

    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)
    

    【讨论】:

      【解决方案5】:

      导入套接字

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

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

      s.getsockname()

      【讨论】:

        【解决方案6】:
        print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())
        

        【讨论】:

          【解决方案7】:

          获取公网IP最简单的方法就是使用这个

          import requests
          
          IP = requests.get('https://api.ipify.org/').text
          print(f'Your IP is: {IP}')
          

          【讨论】:

            【解决方案8】:

            使用http://whatismyip.com源中建议的地址

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

            【讨论】:

            • 请注意,他们说不要每 300 秒执行一次以上
            【解决方案9】:

            您需要连接到外部服务器并从响应中获取您的公共 IP


            像这样

               import requests
            
               myPublic_IP = requests.get("http://wtfismyip.com/text").text.strip()
            
               print("\n[+] My Public IP: "+ myPublic_IP+"\n")
            

            【讨论】:

              猜你喜欢
              • 2020-01-08
              • 2012-02-23
              • 2019-01-11
              • 2013-10-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-01-26
              相关资源
              最近更新 更多