如何使用Python从HTTP响应中获取端口号?

时间:2016-03-21 12:45:46

标签: python python-2.7 sockets http-headers httplib

我正在尝试为某些测试代码模拟网络地址转换。我将虚拟用户映射到高端口号,然后,当我想测试来自用户1的请求时,我从端口6000(用户2,从6001等)发送它。

但是,我无法在响应中看到端口号。

        connection = httplib.HTTPConnection("the.company.lan", port=80, strict=False,   
                                          timeout=10, source_address=("10.129.38.51", 6000))
        connection.request("GET", "/portal/index.html")
        httpResponse = connection.getresponse()
        connection.close()

httpResponse.status为200,但我在响应标头中的任何位置都没有看到端口号。

也许我应该使用一些较低级别的套接字功能?如果是这样,哪个最简单并支持HTTP和FTP?顺便说一句,我只想使用内置模块,我不需要安装任何模块。

[更新]我应该更清楚;我确实需要获得响应中收到的实际端口号,而不仅仅是记住它。

3 个答案:

答案 0 :(得分:2)

HTTP消息不包含任何有关端口的内容,因此httpResponse将不包含该信息。

但是,对于每个请求,您将需要一个不同的连接对象(将映射到不同的底层套接字),以便您可以从HTTPconnection对象获取该信息。

_, port = connection.source_address

这有帮助吗?

答案 1 :(得分:2)

要完成@TimSpence答案,您可以使用套接字对象作为连接的接口,然后使用某些API将您的数据视为HTTP对象。

host = 'xxx.xxx.xxx.xxx'
port = 80
address = (host, port)

## socket object interface for a TCP connection
listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                socket.IPPROTO_TCP)
listener_socket.bind(address)
listener_socker.listen(MAX_CONNECTIONS)

## new_connection is the connection object you use to handle the data echange
## source_address (source_host, source_port) is the address object
##    source_port is what you're looking for
new_connection, source_address = listener_socket.accept()

data = new_connection.recv(65536)

## handle data as an HTTP object(for example as an HTTP request)

new_connection.close()

答案 2 :(得分:0)

考虑到你的意见,我不得不提供一个新答案。

我虽然您也可以在hostHTTPRespose中添加非标准标题'Host: domain/IP:port',以便客户在收到回复时可以阅读。< / p>


服务器响应:

HTTP/1.1 200 OK
Date: Day, DD Month YYYY HH:MM:SS GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: LENGTH
Last-Modified: Day, DD Month YYYY HH:MM:SS GMT
Server: Name/Version (Platform)
Accept-Ranges: bytes
Connection: close
Host: domain/IP:port                                  #exapmple: the.company.lan:80

<html>
<head>
    <title>Example Response</title>
</head>
<body>
    Hello World!
</body>
</html>


客户端:

connection = httplib.HTTPConnection("the.company.lan", port=80, 
                                    strict=False, timeout=10,
                                    source_address=("10.129.38.51", 6000))

connection.request("GET", "/portal/index.html")
httpResponse = connection.getresponse()

## store a dict with the response headers
## extract your custom header 'host'
res_headers = dict(httpResponse.getheaders());
server_address = tuple(headers['host'].split(':'))

## read the response content
HTMLData = httpResponse.read(CONTENT_LENGTH_HEADER)

connection.close()


这样您就可以server_address作为元组(domain, port)