public static SocksProxyTransport connectViaSocks4Proxy ( String remoteHost , int remotePort , String proxyHost , int proxyPort , String userId ) throws IOException , UnknownHostException { SocksProxyTransport proxySocket = new SocksProxyTransport ( remoteHost , remotePort , proxyHost , proxyPort , SOCKS4 ) ; proxySocket . username = userId ; try { InputStream proxyIn = proxySocket . getInputStream ( ) ; OutputStream proxyOut = proxySocket . getOutputStream ( ) ; InetAddress hostAddr = InetAddress . getByName ( remoteHost ) ; proxyOut . write ( SOCKS4 ) ; proxyOut . write ( CONNECT ) ; proxyOut . write ( ( remotePort >>> 8 ) & 0xff ) ; proxyOut . write ( remotePort & 0xff ) ; proxyOut . write ( hostAddr . getAddress ( ) ) ; proxyOut . write ( userId . getBytes ( ) ) ; proxyOut . write ( NULL_TERMINATION ) ; proxyOut . flush ( ) ; int res = proxyIn . read ( ) ; if ( res == - 1 ) { throw new IOException ( "SOCKS4 server " + proxyHost + ":" + proxyPort + " disconnected" ) ; } if ( res != 0x00 ) { throw new IOException ( "Invalid response from SOCKS4 server (" + res + ") " + proxyHost + ":" + proxyPort ) ; } int code = proxyIn . read ( ) ; if ( code != 90 ) { if ( ( code > 90 ) && ( code < 93 ) ) { throw new IOException ( "SOCKS4 server unable to connect, reason: " + SOCKSV4_ERROR [ code - 91 ] ) ; } throw new IOException ( "SOCKS4 server unable to connect, reason: " + code ) ; } byte [ ] data = new byte [ 6 ] ; if ( proxyIn . read ( data , 0 , 6 ) != 6 ) { throw new IOException ( "SOCKS4 error reading destination address/port" ) ; } proxySocket . setProviderDetail ( data [ 2 ] + "." + data [ 3 ] + "." + data [ 4 ] + "." + data [ 5 ] + ":" + ( ( data [ 0 ] << 8 ) | data [ 1 ] ) ) ; } catch ( SocketException e ) { throw new SocketException ( "Error communicating with SOCKS4 server " + proxyHost + ":" + proxyPort + ", " + e . getMessage ( ) ) ; } return proxySocket ; }
Connect the socket to a SOCKS 4 proxy and request forwarding to our remote host .