使用Python请求时如何获取底层socket

使用Python请求时如何获取底层socket

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

问题描述

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

解决方案

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

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

>>>进口请求>>>进口插座>>>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)

对于非流式套接字,在返回响应对象之前清除文件描述符.据我所知,在这种情况下没有办法获得它.

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?

解决方案

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.

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请求时如何获取底层socket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:16