Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Maheshwari Thakur

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);  
      }
   }
}

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);  

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.