使用 Twisted 查找我的服务器 ip 地址

Find my server ip address with Twisted

如何使用 Twisted 异步查找我的服务器 IP 地址?

我是运行一个ubuntu和一个centos结果总是一样的,下面暴露的方法返回的ip总是:127.0.1.1而不是我真正的私有IP 地址。

编辑:这不是提议的 this question 的副本,我最后一次尝试的灵感来自这个答案,我想要的是一种以异步方式实现此目的的方法。

正在尝试使用 tcp 服务器检索 ip

from twisted.internet import protocol, endpoints, reactor


class FindIpClient(protocol.Protocol):

    def connectionMade(self):
        print self.transport.getPeer()  # prints 127.0.1.1
        self.transport.loseConnection()


def main():
    f = protocol.ClientFactory()
    f.protocol = FindIpClient
    ep = endpoints.clientFromString(reactor, 'tcp:127.0.0.1:1234')
    ep.connect(f)
    reactor.run()

main()

使用reactor.resolve

import socket

from twisted.internet import reactor


def gotIP(ip):
    print(ip)  # prints 127.0.1.1
    reactor.stop()


reactor.resolve(socket.getfqdn()).addCallback(gotIP)
reactor.run()

这行得通,但我不确定它的异步性

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
s.setblocking(False)
local_ip_address = s.getsockname()[0]
print(local_ip_address)  # prints 10.0.2.40

如何异步获取我的私有 IP 地址?

这是我的 /etc/hosts 如果它可以帮助:

127.0.0.1 localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
127.0.1.1 mymachine mymachine

我不知道为什么我的主机中有 127.0.1.1 mymachine mymachine 顺便说一句:/

我最终保留了这个解决方案,因为它不能太长 :

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))
s.setblocking(False)
local_ip_address = s.getsockname()[0]
print(local_ip_address)  # prints 10.0.2.40

来自Python Twisted: restricting access by IP address

d = self.transport.getHost () ; print d.type, d.host, d.port

不适用于某些协议,例如接收广播 UDP