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 = "192.168.1.1";
// 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 ("192.168.1.1"). 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.
Output:
When you run the program, you should see the following output:
Converted IPAddress: 192.168.1.1
IPAddress Bytes: 192.168.1.1
Comments (0)