0

Is there a static method I can use to parse a String to check if it is an IP address, instead of having to initialize a new System.Net.IPAddress instance?

This is what I am trying to achieve

System.Net.IPAddress throwawayIpAddress = new System.Net.IPAddress(Encoding.ASCII.GetBytes("127.0.0.1"));

System.Net.IPAddress.TryParse(baseUri.Host, out throwawayIpAddress);

baseUri is a Uri variable, and Host is a string. I am looking for something simpler such as:

System.Net.IPAddress.TryParse(baseUri.Host, out  new System.Net.IPAddress(Encoding.ASCII.GetBytes("127.0.0.1"));

Due to the fact that the TryParse() method expects a String and an out IPAddress reference, I cannot pass null or a throwaway object directly.

Appreciate your advice on a simpler way to parse a String to test if it is an IP Address.

Hanxue
  • 12,243
  • 18
  • 88
  • 130
  • Language error - given that throwawayIpAddress is used as OUT, there is no Need to initialize it. This actually should throw some warning. Just put it to "null", not to new ....IpAddress. It is an OUT Parameter, it is overwritten away anyway. I am quite sure you get a warning or even an error, though, using an already initialized variable as out Parameter. – TomTom Dec 26 '12 at 08:41

3 Answers3

4
public static bool IsValidIpAddress(this string s)
{
    IPAddress dummy;
    return IPAddress.TryParse(s, out dummy);
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90
1

IPAddress.TryParse expects and out parameters. That parameter doesn't have to be initialized. For your code it can be:

System.Net.IPAddress throwawayIpAddress; //No need to initialize it
if(System.Net.IPAddress.TryParse(baseUri.Host, out throwawayIpAddress))
{
//valid IP address
}
{
//Invalid IP address
}

If the parsing is successful then your object throwawayIpAddress will have the valid IP address, you can use it further in the code or ignore it if you want.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

you can use regex

var isValidIP = Regex.IsMatch(stringValue, @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52