Retrieve the subdomain from a URL in C#

Sep 20, 2006

Yesterday I had to come up with a method that retrieved the subdomain from the current web request on an ASP.NET website. I thought that the System.Uri class contained that information in an easy retrievable way, but no. 

Here’s what I came up with instead. It still uses the System.Uri to find the subdomain.

/// <summary>

/// Retrieves the subdomain from the specified URL.

/// </summary>

/// <param name="url">The URL from which to retrieve the subdomain.</param>

/// <returns>The subdomain if it exist, otherwise null.</returns>

private static string GetSubDomain(Uri url)

{

  string host = url.Host;

  if (host.Split('.').Length > 1)

  {

    int index = host.IndexOf(".");

    return host.Substring(0, index);

  }

 

  return null;

}

To use it, simply put in the URL of your choice like so:

GetSubDomain(Request.Url);

Update

Based on the comments I've had so far on this post, I've made some changes to the GetSubDomain() method as shown below. Thanks to Anders and Jacob for the comments.

/// Retrieves the subdomain from the specified URL.

/// </summary>

/// <param name="url">The URL from which to retrieve the subdomain.</param>

/// <returns>The subdomain if it exist, otherwise null.</returns>

private static string GetSubDomain(Uri url)

{

  if (url.HostNameType == UriHostNameType.Dns)

  {

    string host = url.Host;

    if (host.Split('.').Length > 2)

    {

      int lastIndex = host.LastIndexOf(".");

      int index = host.LastIndexOf(".", lastIndex - 1);

      return host.Substring(0, index);

    }

  }

 

  return null;

}

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (8) -

Anders
Anders
9/20/2006 1:22:26 PM #

Your version can not find the subdomain for "http://foo.bar.domain.com"; it should return "foo.bar"
You should change it to:
  if (host.Split('.').Length > 2)
  {
    int lastIndex = host.LastIndexOf(".");
  int index = host.LastIndexOf(".", lastIndex-1);
    return host.Substring(0, index);
  }

Mads Kristensen
Mads Kristensen
9/20/2006 3:15:21 PM #

Hi Anders,

You're right. It only works for single subdomains. I'll check your solution out and test it. Good advice. Thanks.

-Mads

 Jacob
Jacob
9/20/2006 6:05:34 PM #

You could also run into a problem if the URL is specified as an IP number -- it will always split into more than one segment, but in fact doesn't have a subdomain.  You could use System.Uri.HostNameType to check.

Keep up the excellent posts!

 Derek
Derek
9/21/2006 11:39:52 PM #

Your second version works, but Split() allocates an entire array of strings, and you're only fetching a count from it. That's pretty rough on the garbage collector. Here's another version which saves some GC strain (and should be faster) ... Smile

    private static string GetSubdomain(Uri uri) {

        string subdomain = null;

        if (uri.HostNameType == UriHostNameType.Dns) {

            string host = uri.Host;

            int lastIndex = host.LastIndexOf('.') - 1;
            if (lastIndex > 0) {
                if ((lastIndex = host.LastIndexOf('.', lastIndex)) != -1) {
                    subdomain = host.Substring(0, lastIndex);
                }
            }
        }

        return subdomain;
    }

 WhoopJack
WhoopJack
9/22/2006 6:19:19 PM #

You could also do the entire string operation on one line using a regular expression like:

subdomain = Regex.Replace(uri.Host, "(.*)(\\..*){2}", "$1");

 Derek
Derek
9/22/2006 8:23:13 PM #

You can compress the fast solution into two lines as well ... I wouldn't though ;)

private static string GetSubdomain(Uri uri) {
    int lastIndex;
    return (uri.HostNameType == UriHostNameType.Dns && (lastIndex = uri.Host.LastIndexOf('.') - 1) > 0 && (lastIndex = uri.Host.LastIndexOf('.', lastIndex)) != -1) ? uri.Host.Substring(0, lastIndex) : null;
}

 Damien Guard
Damien Guard
9/22/2006 10:31:08 PM #

The problem here is that a username in the format user.name may appear in the uri/url before the host name, e.g.

http://mads.kristensen:password@mysub.domain.com/something/else/here.aspx

You might want to use your technique in conjunction with my URL parsing class from my blog which splits up the various parts.  You could apply your code to the .HostName property.

www.damieng.com/.../...nd_manipulation_in_NET.aspx

[)amien

aniscartujo
aniscartujo United States
11/28/2007 11:40:55 AM #

Good code, but will not work with tlds with multiple dots... ex .co.uk...

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.