eugeneK
eugeneK

Reputation: 11116

How to extract website hostname from full url using VB.NET?

I get ReffererUrl from current User, if refferer is exists i need to extract hostname without .com/.co.uk .... etc. value from it. So if ReffererUrl is http://main.something.biz/sup.aspx?r=e3432r3 i want to get just "something".

Doesn't matter whether it is Regex or something else.

thanks...

Upvotes: 1

Views: 3109

Answers (4)

Andrew-UK
Andrew-UK

Reputation: 1

Extract domain with subdomain if present:-

Public Function ExtractSubAndMainDomainFromURL(URL As String) As String
    '
    ' cut-off any url encoded data
    URL = URL.Split("?"c)(0)
    'return array of segments between slashes
    Dim URLparts() As String = URL.Split("/"c)
    'find first segment with periods/full-stops
    Dim Domain As String = Array.Find(URLparts, Function(x) (x.Contains(".")))
    'check if nothing returned - if necessary
    If IsNothing(Domain) Then Domain = String.Empty 


    Return Domain

End Function

Upvotes: 0

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

HttpContext.Current.Request.ServerVariables("HTTP_HOST")

Upvotes: 0

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

There is no built-in way to do this in the sense you describe, because neither IIS nor ASP.NET knows the difference between the host name and domain name.

You have to write some code to do that.

an example could be:

string hostName=ReffererUrl.split('.')[1];

This code works only if the ReffererUrl look like the one you have posted and you have to make sure the array that the split function return an array with a number of elements greater than 1

Upvotes: 0

Mazhar Karimi
Mazhar Karimi

Reputation:

Note: it is just for your specs only: you can extend it by adding more condition at the end of my code. but i'd say that it wont work when path is like "abc.ss33.video.somthing.co.us"

 Uri u = new Uri("http://main.something.biz/sup.aspx?r=e3432r3");
            string a = u.DnsSafeHost;
            string[] arr1 = a.Split('.');
            string somethinVar = String.Empty;

            if (arr1.Length == 3)
                somethinVar = arr1[1];

Upvotes: 2

Related Questions