This article uses QQ as an object, teach you how to write a SOCKS5 Proxy this chapter mainly introduces the working principle of launch_udp ()
First, SOCKS5 UDP package structure =========================== order: 2 bytes reserved word, must be 0x01 bytes current fragment number1 bytes Address Type X bytes Destination Address 2 Bytes Destination Port number n bytes Data
Second, source code ============================
void Launch_UDP (int udp_proxy_port, const char * udp_proxy_ip, int clt_udp_port) {// port is NOT network orders // record the machine, client, server, and the distal end of the packet the source address struct sockaddr_in servaddr, clientaddr, remoteaddr, inaddr; int inlen INT listenfd; int N; fd_set set; // After writing the received data in the buffer 11th byte, the first 10 Bytes is used to store Header char * thisbuf = & buf [10]; int thissize = bufsz - 10;
Printf ("
// create a UDP SOCKET, UDP protocol does not need to pay attention to listen, accept and conenct memset (& servaddr, 0, sizeof (servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons (udp_proxy_port); servaddr.sin_addr.s_addr = HTONL (INADDR_Any);
Memset (Remoteaddr, 0, SizeOf (RemoteAddr)); RemoteAddr.sin_Family = AF_INET; Listenfd = Socket (AF_INET, SOCK_DGRAM, 0); if (listenfd <0) {p_ERROR ("socket error"); exit (-1); }
IF (Bind (Struct SockAddr *) & Servaddr, SizeOf (Servaddr)) <0) {p_error ("bind error"); exit (-1);
// Use SELECT to monitor if there is information to read FD_ZERO (& Set); FD_SET (Listenfd, & Set);
While (1) {
IF (SELECT (Listenfd 1, & set, NULL, NULL, NULL) <0) {p_error ("select error"); exit (-1);} if (fd_isset (listenfd, & set)) {// UDP protocol Use RECVFROM () to receive data, and obtain the source address N = Recvfrom (Listenfd, thisbuf, thissize, 0, (strunt sockaddr *) & inaddr, & inlen; if (n> = 0) {Debug_Showip (& INADDR, "Received from "," / n "); // Information from client IF ((Thisbuf [0] == 0x0) && (Thisbuf [1] == 0x0) && (htons (inaddr.sin_port) == CLT_UDP_PORT)) {/ / Save the client's address Memcpy (& ClientAddr); if (thisbuf [3]! = 0x1) {// If the destination address type is domain name, advance row resolution Get IP and send Struct Hostent * h; CHAR TMP [256]; Int Seg; Strncpy (TMP, & thisbuf [5], Thisbuf [4]); TMP [thisbuf [4]] = 0;
H = gethostByname (TMP); //
// Send to the client Sendto (Listenfd, BUF, N 10, 0, (Struct Sockaddr *) & Clientaddr, SizeOf (ClientAddr));}}}}}}}; printfd); Printf ("
Download the source code of this chapter → mysocks5.c