Validate IP Address in C#


An IP Address is an Internet Protocol address that is a series of numbers assigned to each device on a computer network. In C#, the class IPAddress class in the namespace System.Net deals with IP addresses.

A program that is used to validate an IP address is given as follows −

Example

 Live Demo

using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace IPaddressDemo {
   class Example {
      public static void Main() {
         IPAddress IP;
         Console.WriteLine("Enter the IP Address: ");
         string ipAddr = Console.ReadLine();
         bool flag = IPAddress.TryParse(ipAddr, out IP);
         if (flag)
         Console.WriteLine("{0} is a valid IP address", ipAddr);
         else
         Console.WriteLine("{0} is not a valid IP address", ipAddr);
      }
   }
}

Output

The output of the above program is as follows.

Enter the IP Address: 130.45.78.200
130.45.78.200 is a valid IP address

Now, let us understand the above program.

An object IP is created of the IPAddress class. Then the required IP address is obtained from the user. The IP address is validated using the method TryParse() in the class IPAddress as this methods validates if a string is an IP address or not. The result is stored in flag. Then the if statement is used to print if the string is IP address or not depending on the value in flag. The code snippet for this is as follows −

IPAddress IP;
Console.WriteLine("Enter the IP Address: ");
string ipAddr = Console.ReadLine();
bool flag = IPAddress.TryParse(ipAddr, out IP);
if (flag)
Console.WriteLine("{0} is a valid IP address", ipAddr);
else
Console.WriteLine("{0} is not a valid IP address", ipAddr);

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements