Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPAddress.Parse("localhost") throws error

Tags:

c#

I have a service that takes an ip string and tries to parse it to an IPAdress. Some external services might pass in 127.0.0.1 but there are some passing in localhost, which causes problems.

So the first one works but the second one throws an error

try 
{
    var foo = IPAddress.Parse("127.0.0.1");
} 
catch 
{
    Console.WriteLine("parsing failed for foo");
}
        
try 
{
    var bar = IPAddress.Parse("localhost");
} 
catch 
{
    Console.WriteLine("parsing failed for bar");
}

Do I have to check if the ip string equals localhost or is there something I can use for it?


1 Answers

If you want to resolve host names and IP Addresses, you can pass either to Dns.GetHostEntry.

This will give you, in return, a list of possible IP addresses (if it was passed a host name) or a single IP Address (If it was passed an IP Address)

like image 109
Damien_The_Unbeliever Avatar answered Mar 27 '26 03:03

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!