How to config socks proxy in Java NIO

匆匆过客 提交于 2019-12-04 15:10:14

问题


I'm developing a tool which includes forcing all network traffic of application to go across a socks proxy in Java. For old Socket API, I can just set system properties "-DsocksProxyHost=my-host -DsocksProxyPort=my-port", but it doesn't work with NIO.

I tried a solution:

I wrote an NIO SocketChannel, called "ProxySocketChannel" which extends SocketChannel. It contains socks connection and other socks proxy logic. But when I run it, I got an "IllegalSelectorException" in this line of code in "SelectorImpl.register":

if (!(ch instanceof SelChImpl))
        throw new IllegalSelectorException();

sun.nio.ch.SelChImpl is package visible so I can't access it. I tried a tricky solution: I put my "ProxySocketChannel" in package "sun.nio.ch". The compilation passed, but I got an error when running:

java.lang.IllegalAccessError: class sun.nio.ch.ProxySocketChannel cannot access its superinterface sun.nio.ch.SelChImpl

I don't know why the class sun.nio.ch.ProxySocketChannel with package sun.nio.ch still can not access sun.nio.ch.SelChImpl. I think there is some protection for JDK built-in classes. Is there a way to access it?

My JDK Version is 1.6.0_65.

Otherwise, is there a way to setup socks proxy for NIO without change existing code?


回答1:


This is seriously difficult. I wrote an SSLSocketChannel class some years ago and I ended up having to write my own SSLSelectorProvider, SSLSelector, and SSLSelectionKey classes as well. You can't just add a SocketChannel-derived class into the existing infrastructure: it is specifically designed to prevent it.




回答2:


EJP is right, this is hard stuff. You can use a dirty trick to register the OPs to the original SocketChannel and then swap the channel on-the-fly to your own implementation once the OPs are triggered. But the correct approach is to write your own SelectorProvider, Selector and SelectionKey which will make you seriously consider using stunnel for SSL if you can.



来源:https://stackoverflow.com/questions/19487363/how-to-config-socks-proxy-in-java-nio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!