Python - 通过代理使用 socket.gethostbyname [英] Python - Using socket.gethostbyname through proxy

查看:54
本文介绍了Python - 通过代理使用 socket.gethostbyname的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TOR 来代理连接,但在通过 socket.gethostbyname("www.yahoo.com") 代理 DNS 查找时遇到了困难——我了解到它没有通过以下方式发送 DNS 流量通过使用wireshark嗅探流量来代理.这是我正在使用的代码的副本

I'm using TOR to proxy connections but am having difficulty proxying DNS lookups via socket.gethostbyname("www.yahoo.com") -- I learned that it was not sending DNS traffic via proxy by sniffing traffic with wireshark. Here's a copy of the code I'm using

import StringIO
import socket
import socks  # SocksiPy module
import stem.process
from stem.util import term

SOCKS_PORT = 7000

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)

socket.socket = socks.socksocket

def getaddrinfo(*args):
    return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo

socket.gethostbyname("www.yahoo.com") <--- This line is not sending traffic via proxy

非常感谢任何帮助!

推荐答案

您正在 socket 模块中调用 gethostbyname.它对你的 SOCKS 套接字一无所知;它只是与操作系统的名称解析机制进行交互.设置 socket.socket = socks.socksocket 可能会影响通过 socket 模块建立的网络连接,但该模块不会直接连接到 DNS 服务器来执行名称解析,因此替换 socket.socket 对此行为没有影响.

You're calling gethostbyname in the socket module. It doesn't know anything about your SOCKS socket; it is simply interacting with your operating system's name resolution mechanisms. Setting socket.socket = socks.socksocket may affect network connections made through the socket module, but the module does not make direct connections to DNS servers to perform name resolution so replacing socket.socket has no impact on this behavior.

如果您只是使用主机名在 socks.socksocket 对象上调用 connect(...) 方法,代理将通过 SOCKS 执行名称解析:

If you simply call the connect(...) method on a socks.socksocket object using a hostname, the proxy will perform name resolution via SOCKS:

s = socks.socksocket()
s.connect(('www.yahoo.com', 80))

如果您确实想通过 SOCKS 连接执行原始 DNS 查询,您需要找到一个 Python DNS 模块,您可以向该模块提供您的 socksocket 对象.

If you actually want to perform raw DNS queries over your SOCKS connection, you'll need to find a Python DNS module to which you can provide your socksocket object.

这篇关于Python - 通过代理使用 socket.gethostbyname的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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