gpt4 book ai didi

python - Twisted HTTP 客户端访问对端IP(服务器)

转载 作者:行者123 更新时间:2023-12-01 03:19:59 26 4
gpt4 key购买 nike

如何在此 Twisted HTTP 客户端示例中访问远程对等 IP? (来自 Twisted 文档)

使用此示例:

from sys import argv
from pprint import pformat

from twisted.internet.task import react
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers


def cbRequest(response):
#print 'Response version:', response.version
#print 'Response code:', response.code
#print 'Response phrase:', response.phrase
#print 'Response headers:'
#print pformat(list(response.headers.getAllRawHeaders()))
poweredby = response.headers.getRawHeaders("X-Powered-By")
server = response.headers.getRawHeaders("Server")


print poweredby
print server

d = readBody(response)
d.addCallback(cbBody)
return d

def cbBody(body):
print 'Response body:'
#print body

def main(reactor, url=b"http://www.example.com/"):
agent = Agent(reactor)
d = agent.request(
'GET', url,
Headers({'User-Agent': ['Twisted Web Client Example']}),
None)
d.addCallback(cbRequest)



return d

react(main, argv[1:])

在互联网和SO上搜索后,我发现它可以从以下位置读取:

self.xmlstream.transport.getHandle().getpeername()

self.transport.getPeer()

但是我不知道“self”指的是哪个类以及将其放在示例代码中的何处?

有什么帮助吗?尖端?有想法吗?

谢谢

最佳答案

虽然您必须破解一些抽象层并触及私有(private)属性,但可以获得地址:

from __future__ import print_function
from twisted.web.client import Agent
from twisted.internet.task import react
from twisted.internet.protocol import Protocol
from twisted.internet.defer import Deferred

class ReadAddress(Protocol):
def __init__(self):
self.result = Deferred()

def connectionMade(self):
self.result.callback(self.transport._producer.getPeer())

def readAddress(response):
p = ReadAddress()
response.deliverBody(p)
return p.result

@react
def main(reactor):
a = Agent(reactor)
d = a.request(b"GET", b"http://www.google.com/")
d.addCallback(readAddress)
d.addCallback(print)
return d

理想情况下,应该有一个更简单的(公共(public)!)接口(interface)来检索这样的信息。如果您可以在 Twisted 跟踪器中提出功能请求,那就太好了。

关于python - Twisted HTTP 客户端访问对端IP(服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42021601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com