[Edit]
+
0
-
0

C# HTTP request example with client socket

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
using System; using System.Net; using System.Net.Sockets; using System.Text; public class Program { public static void Main() { string host = "dirask.com"; int port = 80; IPHostEntry entry = Dns.GetHostEntry(host); // getting avaialble IP addresses from DNS using host name Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { // connecting: socket.Connect(entry.AddressList, port); // request: string requestText = "GET / HTTP/1.1\n\r" + "Host: " + host + "\n\r" + ""; byte[] requestBytes = Encoding.UTF8.GetBytes(requestText); socket.Send(requestBytes); // response: byte[] responseBuffer = new byte[1024]; int responseSize = socket.Receive(responseBuffer); string responseText = Encoding.UTF8.GetString(responseBuffer, 0, responseSize); Console.WriteLine(responseText); // HTTP/1.1 400 Bad Request // Server: cloudflare // Date: Thu, 24 Mar 2022 20:40:49 GMT // Content-Type: text/html // Content-Length: 155 // Connection: close // CF-RAY: - // // <html> // <head><title>400 Bad Request</title></head> // <body> // <center><h1>400 Bad Request</h1></center> // <hr><center>cloudflare</center> // </body> // </html> } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } finally { // cleaning: socket.Dispose(); // or: socket.Shutdown(SocketShutdown.Both); with socket.Close(); } } }