summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/btr/proxy/util/SocksTester.java
blob: 5e8bfda79ec2c58c9c013223e4231f369b1381a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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;
	}
	
}