Search code examples
c#stringhttptcprequest

How to retrieve host from string


I have a request as a string (due to working on tcp level) and I would like to only get the host:

GET http://www.mrjacks.nl/ HTTP/1.1
cache - control: no - cache
Postman - Token: 037a5930 - 715d - 477d - a1d2 - d9445e6f675c
User - Agent: PostmanRuntime / 7.2.0
Accept: */*
Host: www.mrjacks.nl
accept-encoding: gzip, deflate
Connection: keep-alive

In this case I want to get "www.mrjacks.nl".

The programming languague I'm using is C#.

Does anyone have any idea on how to get this url? Through Regex or some other Class? I'm new to regex and I've tried messing around with it a little bit, but without success


Solution

  • Well it's not so hard to do some string manipulations. First thing to do is to search the line with "Host:" word and when you find it - remove the "Host: " word from that line. The leftover will be the address.

    string s = @"GET http://www.mrjacks.nl/ HTTP/1.1
                 cache - control: no - cache
                 Postman - Token: 037a5930 - 715d - 477d - a1d2 - d9445e6f675c
                 User - Agent: PostmanRuntime / 7.2.0
                 Accept: */*
                 Host: www.mrjacks.nl
                 accept-encoding: gzip, deflate
                 Connection: keep-alive";
    var lines = s.Split('\n');
    string result = "no result";
    foreach(var line in lines)
    {
        if(line.StartsWith("Host:"))
        {
            result = line.Replace("Host: ", "");
            break;
        }
    }
    Console.WriteLine(result);