Get host domain from URL?
You can use Request
object or Uri
object to get host of url.
Using Request.Url
string host = Request.Url.Host;
Using Uri
Uri myUri = new Uri("http://www.contoso.com:8080/");
string host = myUri.Host; // host is "www.contoso.com"
Get domain name from given url
If you want to parse a URL, use java.net.URI
. java.net.URL
has a bunch of problems -- its equals
method does a DNS lookup which means code using it can be vulnerable to denial of service attacks when used with untrusted inputs.
"Mr. Gosling -- why did you make url equals suck?" explains one such problem. Just get in the habit of using java.net.URI
instead.
public static String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}
should do what you want.
Though It seems to work fine, is there any better approach or are there some edge cases, that could fail.
Your code as written fails for the valid URLs:
httpfoo/bar
-- relative URL with a path component that starts withhttp
.HTTP://example.com/
-- protocol is case-insensitive.//example.com/
-- protocol relative URL with a hostwww/foo
-- a relative URL with a path component that starts withwww
wwwexample.com
-- domain name that does not starts withwww.
but starts withwww
.
Hierarchical URLs have a complex grammar. If you try to roll your own parser without carefully reading RFC 3986, you will probably get it wrong. Just use the one that's built into the core libraries.
If you really need to deal with messy inputs that java.net.URI
rejects, see RFC 3986 Appendix B:
Appendix B. Parsing a URI Reference with a Regular Expression
As the "first-match-wins" algorithm is identical to the "greedy"
disambiguation method used by POSIX regular expressions, it is
natural and commonplace to use a regular expression for parsing the
potential five components of a URI reference.The following line is the regular expression for breaking-down a
well-formed URI reference into its components.^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
12 3 4 5 6 7 8 9
The numbers in the second line above are only to assist readability;
they indicate the reference points for each subexpression (i.e., each
paired parenthesis).
Get The Current Domain Name With Javascript (Not the path, etc.)
How about:
window.location.hostname
The location
object actually has a number of attributes referring to different parts of the URL
How to get domain name from URL
I once had to write such a regex for a company I worked for. The solution was this:
- Get a list of every ccTLD and gTLD available. Your first stop should be IANA. The list from Mozilla looks great at first sight, but lacks ac.uk for example so for this it is not really usable.
- Join the list like the example below. A warning: Ordering is important! If org.uk would appear after uk then example.org.uk would match org instead of example.
Example regex:
.*([^\.]+)(com|net|org|info|coop|int|co\.uk|org\.uk|ac\.uk|uk|__and so on__)$
This worked really well and also matched weird, unofficial top-levels like de.com and friends.
The upside:
- Very fast if regex is optimally ordered
The downside of this solution is of course:
- Handwritten regex which has to be updated manually if ccTLDs change or get added. Tedious job!
- Very large regex so not very readable.
How to get current domain name in ASP.NET
Using Request.Url.Host
is appropriate - it's how you retrieve the value of the HTTP Host:
header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858
is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority
.
Furthermore, it is not valid to get somedomain.com
from www.somedomain.com
because a webserver could be configured to serve a different site for www.somedomain.com
compared to somedomain.com
, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.')
works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config
) is a red-herring.
Extract hostname name from string
There is no need to parse the string, just pass your URL as an argument to URL
constructor:
const url = 'http://www.youtube.com/watch?v=ClkQA2Lb_iE';
const { hostname } = new URL(url);
console.assert(hostname === 'www.youtube.com');
Parsing domain from a URL
Check out parse_url()
:
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
parse_url
doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.
Related Topics
How to Sort an Observable Collection
"Updatesourcetrigger=Propertychanged" Equivalent for a Windows Phone 7 Textbox
.Net Core 2.2 Can't Be Selected in Visual Studio Build Framework
How to Convert Ticks to a Date Format
Windows.Ui.Notifications Is Missing
Why Are C# 4 Optional Parameters Defined on Interface Not Enforced on Implementing Class
Compare Equality Between Two Objects in Nunit
Regex: I Want This and That and That... in Any Order
How to Access Internal Class Using Reflection
One to One Optional Relationship Using Entity Framework Fluent API
Differencebetween Getter-Only Auto Properties and Expression Body Properties
Displaying Arabic Characters in C# Console Application
Verifying That a String Contains Only Letters in C#
Why Do Local Variables Require Initialization, But Fields Do Not