Mohanapriya R Mohanapriya R
Updated date Jul 01, 2024
In this article, we will learn the ins and outs of converting IP addresses to strings in C#.
  • 1.2k
  • 0
  • 0

Converting IPAddress to Strings in C#

IPAddress is a class in C# that encapsulates an IP address. It can represent both IPv4 and IPv6 addresses. When working with IPAddress, you may need to convert it to different string formats based on your requirements.

 

using System;
using System.Net;

class Program
{
    static void Main()
    {
        // Creating an IPAddress instance for an IPv4 address
        IPAddress ipAddress = IPAddress.Parse("192.168.1.1");

        // Converting IPAddress to string
        string ipAddressString = ipAddress.ToString();

        // Displaying the result
        Console.WriteLine("IP Address as String: " + ipAddressString);
    }
}

Output:

IP Address as String: 192.168.1.1

Converting IPAddress to Byte Array

Sometimes, you might need to work with the raw byte representation of an IPAddress. This can be useful in network-related tasks. 

using System;
using System.Net;

class Program
{
    static void Main()
    {
        // Creating an IPAddress instance for an IPv4 address
        IPAddress ipAddress = IPAddress.Parse("192.168.1.1");

        // Converting IPAddress to byte array
        byte[] ipAddressBytes = ipAddress.GetAddressBytes();

        // Displaying the result
        Console.WriteLine("IP Address as Byte Array: " + BitConverter.ToString(ipAddressBytes));
    }
}

Output:

IP Address as Byte Array: C0-A8-01-01

Comments (0)

There are no comments. Be the first to comment!!!