Regex for extracting second level domain from FQDN?

Posted by Bob on Stack Overflow See other posts from Stack Overflow or by Bob
Published on 2009-11-21T04:45:06Z Indexed on 2010/06/10 1:12 UTC
Read the original article Hit count: 348

Filed under:
|

I can't figure this out. I need to extract the second level domain from a FQDN. For example, all of these need to return "example.com":

  1. example.com
  2. foo.example.com
  3. bar.foo.example.com
  4. example.com:8080
  5. foo.example.com:8080
  6. bar.foo.example.com:8080

Here's what I have so far:

    Dim host = Request.Headers("Host")
    Dim pattern As String = "(?<hostname>(\w+)).(?<domainname>(\w+.\w+))"
    Dim theMatch = Regex.Match(host, pattern)
    ViewData("Message") = "Domain is: " + theMatch.Groups("domainname").ToString

It fails for example.com:8080 and bar.foo.example.com:8080. Any ideas?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about vb.net