Pregunta

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.

¿Fue útil?

Solución 2

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.

Otros consejos

public static bool IsValidIpAddress(this string s)
{
    IPAddress dummy;
    return IPAddress.TryParse(s, out dummy);
}

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]?)$")
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top