This is a creation in Article, where the information may have evolved or changed.
Use the go language to implement the SOCKS5 proxy server, followed by the SSH remote agent, user authentication, balance load some bar
First listen on port 8080, loop over TCP connections
server, err := net.Listen("tcp", ":8080")if err != nil {log.Panic(err)}defer server.Close()log.Println("开始接受连接")for {client, err := server.Accept()if err != nil {log.Println(err)return}log.Println("一个新连接")go socks5Proxy(client)}
The Socks5proxy function is used to implement the SOCK5 proxy
First introduce the SOCK5 proxy protocol
specific to see https://www.zybuluo.com/zwh8800/note/347444
client:0x05 0x02 0x00 0x02 or 0x05 0x01 0x00 (mainly user authentication, we ignore, directly return 0x05 0x00)
server:0x05 0x00
client:0x05 0x01 0x00 0x01 ... or 0x05 0x01 0x00 0x03 ... (0x01 is followed by Ip+port, 0x02 is Ip6+port, 0x03 with the Domainname+port, because it is binary, to use binary packet decoding, and then you can directly use net.) dial to connect, go will automatically switch to the domain name to IP, so it can be used directly)
server:0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 (when the server is determined to be able to perform proxy return determination)
Then there is two Io. Copy for proxy forwarding, here's the code
func socks5Proxy(conn net.Conn) {defer conn.Close()var b [1024]byten, err := conn.Read(b[:])if err != nil {log.Println(err)return}log.Printf("% x", b[:n])conn.Write([]byte{0x05, 0x00})n, err = conn.Read(b[:])if err != nil {log.Println(err)return}log.Printf("% x", b[:n])var addr stringswitch b[3] {case 0x01:sip := sockIP{}if err := binary.Read(bytes.NewReader(b[4:n]), binary.BigEndian, &sip); err != nil {log.Println("请求解析错误")return}addr = sip.toAddr()case 0x03:host := string(b[5 : n-2])var port uint16err = binary.Read(bytes.NewReader(b[n-2:n]), binary.BigEndian, &port)if err != nil {log.Println(err)return}addr = fmt.Sprintf("%s:%d", host, port)}server, err := net.Dial("tcp", addr)if err != nil {log.Println(err)return}conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})go io.Copy(server, conn)io.Copy(conn, server)}