I am currently working on a C# project where I need to validate the text that a user has entered into a text box.
One of the validations required is that it checks to ensure that an IP address has been entered correctly.
How would I go about doing this validation of the IP address.
Thanks for any help you can provide.
Click Start -> Run, type cmd and press Enter, and then type ping 192.168. 1.1 at the prompt window and press Enter. 1. If the result shown as below, it means the IP address is correct and can connect to the router.
You can use IPAddress.Parse Method .NET Framework 1.1. Or, if you are using .NET 4.0, see documentation for IPAddress.TryParse Method .NET Framework 4.
This method determines if the contents of a string represent a valid IP address. In .NET 1.1, the return value is the IP address. In .NET 4.0, the return value indicates success/failure, and the IP address is returned in the IPAddress passed as an out
parameter in the method call.
edit: alright I'll play the game for bounty :) Here's a sample implementation as an extension method, requiring C# 3+ and .NET 4.0:
using System;
using System.Net;
using System.Text.RegularExpressions;
namespace IPValidator
{
class Program
{
static void Main (string[] args)
{
Action<string> TestIP = (ip) => Console.Out.WriteLine (ip + " is valid? " + ip.IsValidIP ());
TestIP ("99");
TestIP ("99.99.99.99");
TestIP ("255.255.255.256");
TestIP ("abc");
TestIP ("192.168.1.1");
}
}
internal static class IpExtensions
{
public static bool IsValidIP (this string address)
{
if (!Regex.IsMatch (address, @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"))
return false;
IPAddress dummy;
return IPAddress.TryParse (address, out dummy);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With