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.

有帮助吗?

解决方案 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.

其他提示

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]?)$")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top