Get domain name from URL

How to Get host domain from URL?

A URI (Uniform Resource Identifier) serves as a standardized representation of a resource that is accessible to your application on the network. It acts as an identifier for locating and retrieving specific resources. Within your application, there are multiple ways to retrieve the host of a URL.

One approach is to utilize the Request object, which provides convenient methods for extracting information about the incoming request, including the host of the URL. Another option is to use the Uri class, which offers a range of properties and methods for parsing and manipulating URIs, including the ability to extract the host component of a given URL. By using these techniques, you can effectively obtain the host information needed for various networking operations within your application.

Get domain name of a url

Using Request.Url

C#
string host = Request.Url.Host.ToLower();
VB.Net
Dim host As String = Request.Url.Host.ToLower()

Using Uri

C#

Uri myUri = new Uri("http://forums.asp.net/t/1110512.aspx?"); string host = myUri.Host;

VB.Net

Dim myUri As New Uri("http://forums.asp.net/t/1110512.aspx?") Dim host As String = myUri.Host

Or u can parse the url using regex

parse the url

How to parse a domain from URL?

C#

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string sURL = "http://forums.asp.net/t/1110512.aspx?"; Regex rg = new Regex("://(?<host>([a-z\\d][-a-z\\d]*[a-z\\d]\\.)*[a-z][-a-z\\d]+[a-z])"); if (rg.IsMatch(sURL)) { MessageBox.Show (rg.Match(sURL).Result("${host}")); } else { MessageBox.Show(string.Empty); } } } }

How to get domain part from URL

VB.Net

Imports System.Text.RegularExpressions Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sURL As String = "http://forums.asp.net/t/1110512.aspx?" Dim rg As New Regex("://(?<host>([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]+[a-z])") If rg.IsMatch(sURL) Then MsgBox(rg.Match(sURL).Result("${host}")) Else MsgBox(String.Empty) End If End Sub End Class

Extract domain name from URL

how to get domain name from UL

An alternative approach that avoids the need for regular expressions or parsing is to utilize the following code snippet:

VB.Net
Request.ServerVariables["HTTP_HOST"]
C#
Request.ServerVariables("HTTP_POST")