Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking that a user has correctly entered an IP Address

Tags:

c#

validation

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.

like image 739
Boardy Avatar asked Oct 14 '11 16:10

Boardy


People also ask

How do you check IP address is correct or not?

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.


1 Answers

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);
        }
    }
}
like image 75
Bryan Boettcher Avatar answered Sep 18 '22 22:09

Bryan Boettcher