Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific subdomain from URL in foo.bar.car.com

Tags:

c#

url

Given a URL as follows:

foo.bar.car.com.au

I need to extract foo.bar.

I came across the following code :

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;     
}

This gives me like foo.bar.car. I want foo.bar. Should i just use split and take 0 and 1?

But then there is possible wwww.

Is there an easy way for this?

like image 359
DarthVader Avatar asked Nov 01 '13 20:11

DarthVader


People also ask

Can a URL have multiple subdomains?

Each domain name can have up to 500 subdomains. You can also add multiple levels of subdomains, such as info.blog.yoursite.com. A subdomain can be up to 255 characters long, but if you have multiple levels in your subdomain, each level can only be 63 characters long.


2 Answers

Given your requirement (you want the 1st two levels, not including 'www.') I'd approach it something like this:

private static string GetSubDomain(Uri url)
{

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

        string host = url.Host;

        var nodes = host.Split('.');
        int startNode = 0;
        if(nodes[0] == "www") startNode = 1;

        return string.Format("{0}.{1}", nodes[startNode], nodes[startNode + 1]);

    }

    return null; 
}
like image 115
AllenG Avatar answered Sep 28 '22 06:09

AllenG


I faced a similar problem and, based on the preceding answers, wrote this extension method. Most importantly, it takes a parameter that defines the "root" domain, i.e. whatever the consumer of the method considers to be the root. In the OP's case, the call would be

Uri uri = "foo.bar.car.com.au";
uri.DnsSafeHost.GetSubdomain("car.com.au"); // returns foo.bar
uri.DnsSafeHost.GetSubdomain(); // returns foo.bar.car

Here's the extension method:

/// <summary>Gets the subdomain portion of a url, given a known "root" domain</summary>
public static string GetSubdomain(this string url, string domain = null)
{
  var subdomain = url;
  if(subdomain != null)
  {
    if(domain == null)
    {
      // Since we were not provided with a known domain, assume that second-to-last period divides the subdomain from the domain.
      var nodes = url.Split('.');
      var lastNodeIndex = nodes.Length - 1;
      if(lastNodeIndex > 0)
        domain = nodes[lastNodeIndex-1] + "." + nodes[lastNodeIndex];
    }

    // Verify that what we think is the domain is truly the ending of the hostname... otherwise we're hooped.
    if (!subdomain.EndsWith(domain))
      throw new ArgumentException("Site was not loaded from the expected domain");

    // Quash the domain portion, which should leave us with the subdomain and a trailing dot IF there is a subdomain.
    subdomain = subdomain.Replace(domain, "");
    // Check if we have anything left.  If we don't, there was no subdomain, the request was directly to the root domain:
    if (string.IsNullOrWhiteSpace(subdomain))
      return null;

    // Quash any trailing periods
    subdomain = subdomain.TrimEnd(new[] {'.'});
  }

  return subdomain;
}
like image 38
HeyZiko Avatar answered Sep 28 '22 05:09

HeyZiko