Mohanapriya R Mohanapriya R
Updated date May 02, 2024
In this article, we will learn how to convert strings to IPAddress in C#. Follow along with a simple program, complete with output examples.

Convert Strings to IPAddress in C#

In C#, the IPAddress class from the System.Net namespace represents an IP address. It provides methods and properties to work with both IPv4 and IPv6 addresses. When dealing with user input or configuration data, it's crucial to be able to convert string representations of IP addresses into IPAddress objects.

using System;
using System.Net;

class Program
    static void Main()
        // Input IP address as a string
        string ipAddressString = "";

        // Convert string to IPAddress
        IPAddress ipAddress = IPAddress.Parse(ipAddressString);

        // Display the result
        Console.WriteLine($"Converted IPAddress: {ipAddress}");

        // Additional actions with the IPAddress object can be performed here

        // Example: Getting bytes of the IPAddress
        byte[] ipAddressBytes = ipAddress.GetAddressBytes();
        Console.WriteLine($"IPAddress Bytes: {string.Join(".", ipAddressBytes)}");

In this example, we start with a string representation of an IPv4 address (""). The IPAddress.Parse method is then used to convert this string into an IPAddress object. Finally, we display the converted IPAddress and perform additional actions if needed, such as obtaining the bytes of the IP address.


When you run the program, you should see the following output:

Converted IPAddress:
IPAddress Bytes:

Comments (0)

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