4

How is the correct way to Parse an IPAddress from String to System.Net.IPAddress on C# with Framework 4.6.

I am trying to implement with Visual Studio 2017 NuGet TCPSimple a TCP/IP Server and Client for testing purposes, but I got a System.FormatException "Input string was not in a correct format".

I have tried different approaches, but they're not working at all!

    private void btnStart_Click(object sender, EventArgs e)
    {
        txtStatus.Text += "Server starting...";

        //var address = System.Net.IPAddress.Parse("10.0.11.174").GetAddressBytes();
        //long m_Address = ((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
        System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));
        //System.Net.IPAddress ip = new System.Net.IPAddress.Parse("127.0.0.1");
        server.Start(ip,Convert.ToInt32(txtPort.Text));
    }

enter image description here

0

3 Answers 3

8

There is an IPAddress.Parse method in the .NET framework to handle this.

IPAddress ip = IPAddress.Parse(txtHost.Text);
1

Look at the documentation for the Parse() method:

public static IPAddress Parse(
    string ipString
)

It's static, and it expects a string. So,

System.Net.IPAddress ip = System.Net.IPAddress.Parse(txtHost.Text);

should do the trick. If this throws a FormatException error it's the user's fault, so catch the exception and display a friendly error message.

1
  • It seemed to me that in System.Net.IPAddress ip = new System.Net.IPAddress.Parse(txtHost.Text); the problem was the "new" instruction so it couldnt find the Parse on the System.Net.IPAddress.....
    – JWBG
    Jul 10, 2018 at 16:53
1

You might want to consider using IPAdress.TryParse() in case you provide an invalid IP. Something like:

using System;
using System.Net;

public class Program
{
    public static void Main()
    {
        string goodIp = "127.0.0.1";
        string badIp = "127.0.O.1";

        IPAddress ip;
        if (IPAddress.TryParse(goodIp, out ip))
        {
            Console.WriteLine("Start your server");
        }

        if (!IPAddress.TryParse(badIp, out ip))
        { 
            Console.WriteLine("Bad IP");
        }
    }
}

Fiddle Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.