Search code examples
c#.netsocketshttpwebrequest

How Create a .NET HttpWebRequest class from a Socket's received byte[]'s


I have a socket that is receiving HTTP requests.

So I have a raw http request in byte[] form from my socket.

I have to study this request - BUT

Instead of reinventing the wheel - can I 'cast' this byte array into a System.Net.HttpWebRequest or something similar?

----- UPDATE ---------

So anyway I couldn't find the answer. By digging a little further though I think it could be done by calling functions in:

HttpApi.dll I think that the HttpWebRequest uses this dll (winxpsp2)

the interesting structure is the HTTP_REQUEST

C++
typedef struct _HTTP_REQUEST {
  ULONG                  Flags;
  HTTP_CONNECTION_ID     ConnectionId;
  HTTP_REQUEST_ID        RequestId;
  HTTP_URL_CONTEXT       UrlContext;
  HTTP_VERSION           Version;
  HTTP_VERB              Verb;
  USHORT                 UnknownVerbLength;
  USHORT                 RawUrlLength;
  PCSTR                  pUnknownVerb;
  PCSTR                  pRawUrl;
  HTTP_COOKED_URL        CookedUrl;
  HTTP_TRANSPORT_ADDRESS Address;
  HTTP_REQUEST_HEADERS   Headers;
  ULONGLONG              BytesReceived;
  USHORT                 EntityChunkCount;
  PHTTP_DATA_CHUNK       pEntityChunks;
  HTTP_RAW_CONNECTION_ID RawConnectionId;
  PHTTP_SSL_INFO         pSslInfo;
}HTTP_REQUEST_V1, *PHTTP_REQUEST_V1;

I have only just started C# so delving into ??COM?? programming is over my head.

AND looking through the ducumentation, I cant see an 'entry' (by which I mean a simple send bytes-> receieve HTTP_REQUEST).

Anyhoo! if anyone wants to point me in the direction of some nice WINDOWS KERNEL MODE HTTP SERVERS INCLUDING SSL then feel free it would be a great read and something to consider for the future.


Solution

  • just replace Socket by using HttpListener. It parses the HTTP request for you, easily.

    Here is an example:

    HttpListener listener = new HttpListener(); 
    // prefix URL at which the listener will listen
    listener.Prefixes.Add("http://localhost:8080/");
    listener.Start();
    Console.WriteLine("Listening...");
    while (true)
    {
        // the GetContext method blocks while waiting for a request.
        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;
    
        // process the request
        // if you want to process request from multiple clients 
        // concurrently, use ThreadPool to run code following from here
        Console.WriteLine("Client IP " + request.UserHostAddress);
    
        // in request.InputStream you have the data client sent
        // use context.Response to respond to client
    }