- Home /
Gethostbyname, get ip address from a url?
I wish to know if there is any function that returns an IP Address from url. I'm using a dynamicIP service to test connectivity.
What I will like to try is something like this:
MasterServer.ipAddress=gethostbyname("www.dynamicIP.com");
Thank you all
Answer by Bunny83 · Aug 01, 2011 at 06:19 PM
This will translate an URL to an IP address but only the first that is received and without error-checking!! If you don't have an internet connections / no dns server connection this will fail. If the URL doesn't exist it will fail too (of course).
// C# using System.Net;
//[...] public static string gethostbyname(string aURL) { PHostEntry Hosts = Dns.GetHostEntry(URL); return Hosts.AddressList[0].ToString(); }
edit
To be more precise: It doesn't translate an URL, only a domain-name e.g. the host-part of the URL
Answer by col000r · Aug 29, 2014 at 07:20 AM
Dns.GetHostEntry does the job, but it only seems to work with bare urls like www.domain.com, no http://www.domain.com, no www.domain.com/subdir/index.html, etc. So I've written this convenient function that takes pretty much any kind of url, strips away the unwanted parts and returns the IP address.
// C#
using System.Net;
public static string GetIP(string url) {
url = url.Replace("http://", ""); //remove http://
url = url.Replace("https://", ""); //remove https://
url = url.Substring(0, url.IndexOf("/")); //remove everything after the first /
try {
IPHostEntry hosts = Dns.GetHostEntry(url);
if(hosts.AddressList.Length > 0) return hosts.AddressList[0].ToString();
} catch {
Debug.Log ("Could not get IP for URL " + url);
}
return null;
}
Answer by sendery · Aug 03, 2011 at 06:00 PM
Thank your, It works, as you said not really well, but at least it returns the IP address.
By the way It doesnt work with web redirections.
And it is "IPHostEntry" instead of "PHostEntry"
Anyway thank you
Your answer
Follow this Question
Related Questions
How to prevent unescaping redirected url?,how to prevent unescaping redirected url? 0 Answers
Network.Instantiate Problem 1 Answer
Unity networkedrigidbody 0 Answers
Parsing a JSON response 1 Answer
Network.Connect returns NoError but no connection? 0 Answers