Share via


how to find whether a string contains HOST NAME or IP ADDRESS

Question

Thursday, August 9, 2007 2:25 PM | 1 vote

hello all,
i have one input variable as a String.
if it is IP Address then i have to find HOSTNAME.
if it is HOSTNAME then i have to find IP Address.
i can use any API for getting IP or HOST only after knowing whether the input is HOST or IP.
any body please help in finding the input is IP or HOST
Regards
R

All replies (6)

Thursday, August 9, 2007 3:30 PM ✅Answered

You could try Dns.GetHostEntry.  It returns an IPHostEntry which you can use the AddressList property and the IPAddress.ToString to compare the IP address to your original string to see if it was an IP Address.  Example:

Code Snippet

  String nameOrAddress = "127.0.0.1";
  IPHostEntry hostEntry = Dns.GetHostEntry(nameOrAddress);
  if(hostEntry.AddressList[0].ToString() == nameOrAddress)
   Console.WriteLine("{0} is IP", nameOrAddress);
  else
   Console.WriteLine("{0} is hostname", nameOrAddress);
  nameOrAddress = "localhost";
  hostEntry = Dns.GetHostEntry(nameOrAddress);
  if(hostEntry.AddressList[0].ToString() == nameOrAddress)
   Console.WriteLine("{0} is IP", nameOrAddress);
  else
   Console.WriteLine("{0} is hostname", nameOrAddress);

 

 

 


Thursday, August 9, 2007 6:16 PM ✅Answered

You sure can use a regular expression

http://www.codeproject.com/dotnet/RegexTutorial.asp has an example of finding an IP address, and should be read if you're starting out with regular expressions

Here it is if you're lazy

((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)

Of course, that will only prove if it is an IP address or not, it doesn't prove that it's a proper host

Anyway, have fun,

-mwalts


Thursday, August 9, 2007 2:44 PM

Check this IPAddress Class. The example in that might help you

 


Thursday, August 9, 2007 3:48 PM

You can also use a regular expression to check if it's a ip-address.

 


Friday, August 10, 2007 4:07 AM

thank you  very much all of u guys


Saturday, August 11, 2007 9:48 AM | 1 vote

Yesterday I read that the IPAddress class has a static TryParse method. This would probably be the best solution for your intention.