【发布时间】:2016-02-04 15:57:36
【问题描述】:
如何使用 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 顺便说一句:/
【问题讨论】:
-
我假设
127.0.1.1是一个错字? -
不,不是,我得到 127.0.1.1
-
为什么需要异步方法?没有长时间运行的操作,您只是创建一个服务器端套接字对象并获取一些关于它的元数据。
-
我不知道
local_ip_address = s.getsockname()[0]可能比其他任何东西都“可能更长”。