How can I get an IP address, given a domain name?
For example: www.test.com
-
What about getting domain name from IP?– MosheMar 17, 2010 at 12:38
-
@Moshe: stackoverflow.com/questions/716748/c-reverse-ip-domain-check– Jørn Schou-RodeMar 17, 2010 at 12:43
4 Answers
You can use the System.Net.Dns
class:
Dns.GetHostAddresses("www.test.com");
-
2Also note it is PLURAL - and not all of them may work at a given time.– TomTomMar 17, 2010 at 12:35
-
1True, but i think it rare case that this method returns more then one address, especially in case of internet domains.– AndreyMar 17, 2010 at 12:37
-
@Brian - six IPs! WOW! so you need to store them all and pick next if one doesn't work.– AndreyMar 17, 2010 at 13:00
-
@RollRoll because not all addresses may be working, which is the point of multiple A Records. Jul 15, 2018 at 3:33
You could use the GetHostAddresses method:
var address = Dns.GetHostAddresses("www.test.com")[0];
-
-
1
-
@Andrey: If more than one, it would just ignore the rest. If 0, I guess it would crash :p– SvishMar 17, 2010 at 12:39
-
2@Moshe, in VB.NET :
Dim address = Dns.GetHostAddresses("www.test.com")(0)
Mar 17, 2010 at 12:40 -
You can get the same results by using:
Dns.GetHostAddresses("yahoo.com");
or
await Dns.GetHostAddressesAsync("yahoo.com");
My answer could be more the same above answers, but here i get the current web app hosted URL / domain name using code and obtained the IP address and from that. I used the code in my C# MVC Web app and its working fine.
Uri myUri = new Uri(((System.Web.HttpContextWrapper)HttpContext).Request.Url.ToString());
var ipAddress = Dns.GetHostAddresses(myUri.Host).FirstOrDefault().ToString();