using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace UDPoverTCP_TunelClient { class GatewayUDP_TCP { private TcpClient tcpClient; private UdpClient udpClient; private const int DATAGRAM_SIZE = 8196; //IPEndPoint object will allow us to read datagrams sent from any source. private IPEndPoint remoteIpEndPoint; public GatewayUDP_TCP(TcpClient tcp_client, UdpClient udp_client) { tcpClient = tcp_client; udpClient = udp_client; remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); } public void relayDatagramFromUDPtoTCP() { try { Byte[] udpData = null; Byte[] dataSize = null; // Get a stream object for reading and writing NetworkStream tcpStream = tcpClient.GetStream(); do { //Console.WriteLine("Waiting for Datagram ..."); // Blocks until a message returns on this socket from a remote host. udpData = udpClient.Receive(ref remoteIpEndPoint); dataSize = System.Text.Encoding.ASCII.GetBytes(udpData.Length.ToString()+'\0'); // Send datagram size. tcpStream.Write(dataSize, 0, dataSize.Length); // Send datagram data. tcpStream.Write(udpData, 0, udpData.Length); } while (udpData.Length != 0); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public void relayDatagramFromTCPtoUDP() { try { NetworkStream tcpStream = tcpClient.GetStream(); int i, udpLength, dataRead, readCount; string s_dataLength; Byte[] dataSize = new Byte[DATAGRAM_SIZE]; Byte[] udpData = new Byte[DATAGRAM_SIZE]; do { readCount = 0; // read datagram size, it finishes with 0 delimiter. do { if ((i = tcpStream.Read(dataSize, readCount, 1)) != 1) return; readCount += i; } while(dataSize[readCount-1]!=0); // Translate data bytes to a ASCII string. s_dataLength = System.Text.Encoding.ASCII.GetString(dataSize, 0, readCount); udpLength = Convert.ToInt32(s_dataLength); // Read dataRead = 0; do { if ((i = tcpStream.Read(udpData, dataRead, udpLength - dataRead)) == 0) return; dataRead += i; } while (dataRead < udpLength); udpClient.Send(udpData, dataRead, remoteIpEndPoint); } while (udpLength != 0); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }