1

正如标题所说,我目前尝试通过 Tor 代理解析主机名。

Tor 在专用服务器 (192.168.1.15) 上运行。获取网站没有问题,但是如果我尝试获取主机的 IP,Java 仍然会直接查找并忽略代理。

我已经尝试过这种方式:

//Trying lib from: www.xbill.org/dnsjava
import org.xbill.DNS.*;
[...]
public void lookup(){
    //Lookup without proxy
    try {
        InetAddress addr = Address.getByName("stackoverflow.com");
        System.out.println(addr);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    //set socks v5 proxy
    //http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies
    System.setProperty("socksProxyHost", "192.168.1.15");
    System.setProperty("socksProxyPort", "9050");

    //trying to resolve with dnsjava
    try {
        Record [] records = new Lookup("stackoverflow.com", Type.A).run();
        for (Record record : records) {
            System.out.println(record);
        }
    } catch (TextParseException e) {
        e.printStackTrace();
    }

    //trying to resolve without lib
    try {
        System.out.println(InetAddress.getByName("stackoverflow.com"));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

public void request(){
    InetSocketAddress torProxyAddress = new InetSocketAddress("192.168.1.15", 9050);
    Proxy torProxy = new Proxy(Proxy.Type.SOCKS, torProxyAddress);
    Socket underlying = new Socket(torProxy);

    InetSocketAddress unresolvedAdr = InetSocketAddress.createUnresolved("stackoverflow.com", 80);

    try {
        underlying.connect(unresolvedAdr);

        BufferedWriter out = new BufferedWriter( new OutputStreamWriter(underlying.getOutputStream()));
        BufferedReader in = new BufferedReader( new InputStreamReader(underlying.getInputStream()));

        out.write("GET / HTTP/1.1\nHost: stackoverflow.com\n\n");
        out.flush();
        String line;
        while((line = in.readLine()) != null){
            System.out.println(line);
        }
    } catch (IOException e) {

    } finally {
        try {
            underlying.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如何强制 Java 通过 tor 代理进行查找?

4

1 回答 1

1

通过 Tor 代理很难做到这一点,因为在不修改或实现自己的 NetAddressNameService 的情况下,无法通过 Tor 路由 InetAddressNameservice。正常的 nslookups 是通过端口 53 (UDP) 完成的,Tor 目前只支持 TCP。

因此,使用 Tor 方式解析主机名,您需要实现自己的“Tor-client”,因为您需要发送 RELAY_RESOLVE 单元(查看tor-spec.txt 第 6.4 章

一种简单的选择是使用SilverTunnel-NG。该库还使用 Tor 网络进行 ns-lookups。

于 2013-11-19T13:39:30.440 回答