Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my SOCKS proxy code throw SocketException: Malformed reply from SOCKS server?

Why does my SOCKS proxy code throw SocketException: Malformed reply from SOCKS server? I've tried to set in URLConnection or other, but this doesn't work. Only thing that worked - chilkat lib, but it's commercial. So, how I, for example, make http request through a ASOCKS proxy? Maybe exist some free lib for that?

For example, that code:

    SocketAddress addr = new InetSocketAddress(proxy_ip, proxy_port);
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
    Socket socket = new Socket(proxy);
    InetSocketAddress dest = new InetSocketAddress("google.com", 80);
    try {
        socket.connect(dest);
    } catch (IOException ex) {
        Logger.getLogger(CheckProxy.class.getName()).log(Level.SEVERE, null, ex);
    }

Throws exception:

java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at proxychecker.CheckProxy.SocksCheck(CheckProxy.java:86)

Where line 86 is "socket.connect(dest);"

like image 354
Pter Avatar asked Nov 30 '14 15:11

Pter


2 Answers

Explanation of this bug: bugs.java.com/view_bug.do?bug_id=6964547

You need to manually change mode in Socket object using this code:

Class clazzSocks  = socket.getClass();
Method setSockVersion  = null;
Field sockImplField = null; 
SocketImpl socksimpl = null; 
try {
  sockImplField = clazzSocks.getDeclaredField("impl");
  sockImplField.setAccessible(true);
  socksimpl  = (SocketImpl) sockImplField.get(socket);
  Class clazzSocksImpl  =  socksimpl.getClass();
  setSockVersion  = clazzSocksImpl.getDeclaredMethod("setV4");
  setSockVersion.setAccessible(true);
  if(null != setSockVersion){
      setSockVersion.invoke(socksimpl);
  }
  sockImplField.set(socket, socksimpl);
} catch (Exception e) {

} 
like image 142
Pter Avatar answered Oct 02 '22 02:10

Pter


SocketException: Malformed reply from SOCKS server

That indicates that you don't have a SOCKS proxy at all. Possibly it is an HTTP proxy.

And note that you asked the wrong question. Your code was correct, it was your premiss that was wrong.

like image 42
user207421 Avatar answered Oct 02 '22 03:10

user207421