Socket proxy implemented with Java (supports SOCKET4 and SOCKET5)

Source: Internet
Author: User

Import java.io.*;
Import java.net.InetAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.nio.ByteBuffer;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Arrays;
Import Java.util.Date;
Import Java.util.concurrent.CountDownLatch;

/** * Created with Intellij idea * * @author: Jiaoyiping * Mail: [email protected] * date:2018/03/01 * time:22:08 * To change this template use File | Settings | Editor | File and Code Templates */public class Mysocket5server implements Runnable {private static final int socks_protocol_4 = 0X 04;private static final int socks_protocol_5 = 0x05;private static final int default_buffer_size = 1024;private static fin Al byte Type_ipv4 = 0x01;private static final byte Type_ipv6 = 0x02;private static final byte Type_host = 0x03;private sta TIC final byte Allow_proxy = 0x5a;private static final byte Deny_proxy = 0x5b;private Socket sourcesocket; @Overridepublic    void Run () {String remoteaddress = sourcesocket.getremotesocketaddress (). toString ();    Log ("Process socket:" + remoteaddress);    InputStream Sourcein = null, Proxyin = NULL;    OutputStream sourceout = null, proxyout = NULL;    Socket proxysocket = null;        try {Sourcein = Sourcesocket.getinputstream (); sourceOUt = Sourcesocket.getoutputstream ();        Gets the type of socket from the protocol header byte[] tmp = new byte[1];        int n = sourcein.read (TMP);            if (n = = 1) {int protocol = tmp[0]; Socket4 if (socks_protocol_4 = = PROTOCOL) {proxysocket = ConvertToSocket4 (Sourcein, Sourceout            );            } else if (socks_protocol_5 = = PROTOCOL) {proxysocket = ConvertToSocket5 (Sourcein, sourceout);            } else {log ("socket protocol error, not SOCKET4 or Socket5"); }//socket convert if (null! = Proxysocket) {Countdownlatch Countdownlatch = new Countdown                Latch (1);                Proxyin = Proxysocket.getinputstream ();                Proxyout = Proxysocket.getoutputstream ();                Transfer (Sourcein, Proxyout, Countdownlatch);                Transfer (Proxyin, Sourceout, Countdownlatch);                try {countdownlatch.await (); } catch (Interruptedexception e) {e.printstacktrace ();        }}} else {log ("SOCKET ERROR:" + tmp.tostring ());    }} catch (IOException e) {e.printstacktrace ();        } finally {Closeio (Sourcein);        Closeio (Proxyin);        Closeio (proxyout);        Closeio (Proxyin);        Closeio (Proxysocket);    Closeio (Sourcesocket); }}public mysocket5server (Socket sourcesocket) {this.sourcesocket = Sourcesocket;}    private static final void log (String message) {DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); System.out.println (Dateformat.format (New Date ()) + "-" + message);    private static void StartServer (int port) {log ("config =>> port=" + port);        Try (serversocket serversocket = new ServerSocket (port)) {SOCKET socket = NULL;        while (socket = serversocket.accept ()) = null) {New Thread (new Mysocket5server (socket)). Start (); } log ("Close socket (this nEver happen) ");    } catch (IOException e) {e.printstacktrace (); }}private socket ConvertToSocket4 (InputStream inputstream, OutputStream outputstream) throws IOException {socket proxy    Socket = null;    byte[] tmp = new BYTE[3];    Inputstream.read (TMP); Request Agreement | vn1| cd1| dstport2| dstip4|    null1|    int port = BYTEBUFFER.WRAP (TMP, 1, 2). Asshortbuffer (). Get () & 0xFFFF;    String host = GetHost ((byte) 0x01, InputStream);    Inputstream.read (); Returns a 8-byte response protocol: | vn1| cd1| dstport2|    Dstip 4|    byte[] response = new BYTE[8];        try {proxysocket = new Socket (host, Port);        RESPONSE[1] = Allow_proxy;    Log ("Connect" + tmp[1] + "HOST:" + Host + ", Port:" + port);        } catch (Exception e) {response[1] = Deny_proxy;    Log ("Connect error,host:" + Host + ", Port:" + port);    } outputstream.write (response);    Outputstream.flush (); return proxysocket;} Private Socket ConvertToSocket5 (InputStream inputstream, OutputStream outputstream) throws IOException {Socket proxysocket = null;    Processing SOCKS5 header information (login not supported) byte[] tmp = new byte[2];    Inputstream.read (TMP);    byte method = Tmp[1];        if (0x02 = = Tmp[0]) {method = 0x00;    Inputstream.read ();    } tmp = new byte[]{0x05, method};    Outputstream.write (TMP);    Outputstream.flush ();    byte cmd = 0;    TMP = new BYTE[4];    Inputstream.read (TMP);    Log ("Proxy header is:" + arrays.tostring (TMP));    cmd = tmp[1];    String host = GetHost (Tmp[3], inputstream);    TMP = new byte[2];    Inputstream.read (TMP);    int port = BYTEBUFFER.WRAP (TMP). Asshortbuffer (). Get () & 0xFFFF;    Log ("Connect host:" + Host + ":p ORT:" + port);    Bytebuffer RSV = bytebuffer.allocate (10);    Rsv.put ((byte) 0x05);    Object resulttmp = null;            try {if (0x01 = = cmd) {resulttmp = new Socket (host, Port);        Rsv.put ((byte) 0x00);            } else if (0x02 = = cmd) {resulttmp = new ServerSocket (port);        Rsv.put ((byte) 0x00);} else {rsv.put ((byte) 0x05);        Resulttmp = null;        }} catch (Exception e) {rsv.put ((byte) 0x05);    Resulttmp = null;    } rsv.put ((byte) 0x00);    Rsv.put ((byte) 0x01);    Rsv.put (Sourcesocket.getlocaladdress (). getaddress ());    Short LocalPort = (short) ((Sourcesocket.getlocalport ()) & 0xFFFF);    Rsv.putshort (LocalPort);    TMP = Rsv.array ();    Outputstream.write (TMP);    Outputstream.flush ();        if (null! = resulttmp && 0x02 = = cmd) {serversocket SS = (serversocket) resulttmp;        try {resulttmp = ss.accept ();        } catch (Exception e) {} finally {Closeio (ss); }} return (Socket) resulttmp;} private void Transfer (InputStream in, outputstream out, Countdownlatch latch) {new Thread ((), {byte[] Byt        ES = new Byte[default_buffer_size];        int count = 0; try {while (0 < (count = In.read (bytes))) {out.write (bytes, 0, count);            Out.flush ();            }} catch (IOException e) {log ("Conversion error occurred");        E.printstacktrace ();        } if (latch! = null) {Latch.countdown (); }}). Start ();}        private void Closeio (closeable closeable) {if (closeable! = null) {try {closeable.close ();        } catch (IOException e) {e.printstacktrace ();    }}}private string GetHost (byte type, InputStream InputStream) throws IOException {string host = null;    byte[] tmp = NULL;            Switch (type) {case type_ipv4:tmp = new Byte[4];            Inputstream.read (TMP);            Host = Inetaddress.getbyaddress (TMP). gethostaddress ();        Break            Case type_ipv6:tmp = new BYTE[16];            Inputstream.read (TMP);            Host = Inetaddress.getbyaddress (TMP). gethostaddress ();        Break            Case Type_host:int count = Inputstream.read (); TMP = newByte[count];            Inputstream.read (TMP);        Host = new String (TMP);    Default:break; } return host;    public static void Main (string[] args) {java.security.Security.setProperty ("Networkaddress.cache.ttl", "86400"); Mysocket5server.startserver (1033);}}

Socket proxy implemented with Java (supports SOCKET4 and SOCKET5)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.