Trying to do something like a proxy server to block resources on the host. Here something inexplicable is happening for me. Sometimes the site is loaded, when the error is not loaded and crashes.
SocketExceptionaddress is not compatible with the protocol.
The error pops up in myRerouting.Connect(myIPEndPoint);
Tell me, please, what is wrong. Here is the code itself:
class Program { private static string[] _BlackList = { "vkontakte.ru", "vk.com", "odnoklassniki.ru", "facebook.com" }; static void Main(string[] args) { // слушаем локальный апишник (127.0.0.1) и порт 8888 TcpListener myTCP = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888); // поехали! myTCP.Start(); while (true) { // смотрим, есть запрос или нет if (myTCP.Pending()) { // запрос есть // передаем его в отдельный поток Thread t = new Thread(ExecuteRequest); t.IsBackground = true; t.Start(myTCP.AcceptSocket()); } } myTCP.Stop(); } private static void ExecuteRequest(object arg) { Socket myClient = (Socket)arg; // соединяемся if (myClient.Connected) { // получаем тело запроса byte[] httpRequest = ReadToEnd(myClient); // ищем хост и порт Regex myReg = new Regex(@"Host: (((?<host>.+?):(?<port>\d+?))|(?<host>.+?))\s+", RegexOptions.Multiline | RegexOptions.IgnoreCase); Match m = myReg.Match(System.Text.Encoding.ASCII.GetString(httpRequest)); string host = m.Groups["host"].Value; int port = 0; // если порта нет, то используем 80 по умолчанию if (!int.TryParse(m.Groups["port"].Value, out port)) { port = 80; } // получаем апишник по хосту IPHostEntry myIPHostEntry = Dns.GetHostEntry(host); // создаем точку доступа IPEndPoint myIPEndPoint = new IPEndPoint(myIPHostEntry.AddressList[0], port); // создаем сокет и передаем ему запрос using (Socket myRerouting = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { myRerouting.Connect(myIPEndPoint); if (myRerouting.Send(httpRequest, httpRequest.Length, SocketFlags.None) != httpRequest.Length) { Console.WriteLine("При отправке данных удаленному серверу произошла ошибка..."); } else { if (_BlackList != null && Array.IndexOf(_BlackList, host.ToLower()) != -1) { byte[] response = Encoding.ASCII.GetBytes("HTTP/1.1 403 Forbidden\r\nContent-Type: text/html\r\nContent-Length: 19\r\n\r\nDostup zapreschen!"); myClient.Send(response, response.Length, SocketFlags.None); return; } else { // получаем ответ byte[] httpResponse = ReadToEnd(myRerouting); // передаем ответ обратно клиенту if (httpResponse != null && httpResponse.Length > 0) { myClient.Send(httpResponse, httpResponse.Length, SocketFlags.None); } } } } myClient.Close(); } } private static byte[] ReadToEnd(Socket mySocket) { byte[] b = new byte[mySocket.ReceiveBufferSize]; int len = 0; using (MemoryStream m = new MemoryStream()) { while (mySocket.Poll(1000000, SelectMode.SelectRead) && (len = mySocket.Receive(b, mySocket.ReceiveBufferSize, SocketFlags.None)) > 0) { m.Write(b, 0, len); } return m.ToArray(); } } }