使用Python请求时如何获取基础套接字 [英] How to get the underlying socket when using Python requests

查看:172
本文介绍了使用Python请求时如何获取基础套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,它使用请求库创建了许多短暂的同时连接.我特别需要找出每个连接使用的源端口,并且我认为我需要为此访问底层套接字.有没有办法通过响应对象来做到这一点?

I have a Python script that creates many short-lived, simultaneous connections using the requests library. I specifically need to find out the source port used by each connection and I figure I need access to the underlying socket for that. Is there a way to get this through the response object?

推荐答案

对于流连接(使用stream=True参数打开的连接),可以在响应对象上调用.raw.fileno()方法以获取打开的文件描述符.

For streaming connections (those opened with the stream=True parameter), you can call the .raw.fileno() method on the response object to get an open file descriptor.

您可以使用socket.fromfd(...)方法从描述符创建Python套接字对象:

You can use the socket.fromfd(...) method to create a Python socket object from the descriptor:

>>> import requests
>>> import socket
>>> r = requests.get('http://google.com/', stream=True)
>>> s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)
>>> s.getpeername()
('74.125.226.49', 80)
>>> s.getsockname()
('192.168.1.60', 41323)

对于非流套接字,在返回响应对象之前清理文件描述符.据我所知,在这种情况下是无法实现的.

For non-streaming sockets, the file descriptor is cleaned up before the response object is returned. As far as I can tell there's no way to get it in this situation.

这篇关于使用Python请求时如何获取基础套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆