Socket exception in sending HTTP request without Connection header using sockets

Viewed 1170

When I use the following code to send HTTP GET request using sockets in C#

    IPEndPoint RHost = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), 80);
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.Connect(RHost);
    String req = "GET / HTTP/1.1\r\nHost: awebsite.com\r\n\r\n";

    socket.Send(Encoding.ASCII.GetBytes(req), SocketFlags.None);
    int bytes = 0;
    byte[] buffer = new byte[256];
    var result = new StringBuilder();

    do
    {
        bytes = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
        result.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
    }
    while (bytes > 0);

I get

System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'

and when I add Connection: Close header to the request, it is working without any problem. But using Repeater tool in the Burp Suite I am able to send and receive a response from the server without setting Connection: Close header.

Notes:

  • I have to use socket.
  • I am facing this problem just with few websites, not every website
1 Answers
Related