package com.btr.proxy.util; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.util.Arrays; public class SocksTester { private static byte[] SOCKS_4_HANDSHAKE = new byte[] { 0x04, // Version 0x01, // establish connection 0x23, (byte)0x82, // Port 9090 0x01, 0x01, 0x01, 0x01, // 1.1.1.1 0x46, 0x72, 0x65, 0x64, 0x00 // Fred\0 }; /** * Connect to the given host:port and try to talk SOCKS4 * to it, requesting a connection to 1.1.1.1:9090. * If the server replies using the SOCKS protocol, * we return true, false otherwise. * If mustAccept is set, we additionally check that * the SOCKS proxy actually granted the outgoing connection * request. * * @param host * @param port * @return */ public static boolean trySocks4(String host, int port, boolean mustAccept) { Arrays.copyOf(SOCKS_4_HANDSHAKE, SOCKS_4_HANDSHAKE.length); try (Socket socket = new Socket(Proxy.NO_PROXY)) { socket.connect(new InetSocketAddress(host, port), 1000); byte[] buffer = new byte[13]; buffer[0] = 0x04; buffer[1] = 0x01; InetSocketAddress google = new InetSocketAddress("www.google.com", 80); google.getAddress().getAddress(); socket.getOutputStream().write(SOCKS_4_HANDSHAKE); int num = socket.getInputStream().read(buffer); // Wrong length or wrong header if (num < 8 || buffer[0] != 0x00) return false; if (mustAccept) { // Must be accept code if (buffer[1] != 0x5A) return false; } else { // Must be any valid return code if (buffer[1] < 0x5A || buffer[1] > 0x5D) return false; } } catch (Exception e) { return false; } return true; } }