Convert an Ipaddress to string

Asked

Viewed 286 times

2

This code retrieves the gateway standard, but I can’t convert the result to string and put on a label.

public static IPAddress GetDefaultGateway()
{
    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
    if(card == null) return null;
    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
    return address.Address;
}

I’m trying like this:

IPAddress gatway;
gatway = GetDefaultGateway();
if(gatway != null)
{
    label8.Text = gatway.Address.ToString(); //Aqui da erro...
}
  • Which error occurs?

  • An unhandled Exception of type 'System.Net.Sockets.Socketexception' occurred in System.dll Additional information: There is no support for the attempted operation for the object type to which reference is made

2 answers

1

Try to assign label text as follows:
string n = Convert.ToString(gatway.Address);
label8.Text = n;

  • I got it otherwise but is returning the IPV6 and I want IPV4

1


This property is obsolete. Use the method GetAddressBytes() that will return a array bytes with each part of the IP. Then just give one Join() to form the text. Something like this (using LINQ):

IPAddress gateway = GetDefaultGateway();
if (gateway != null) {
    label8.Text = string.Join(".", gateway.GetAddressBytes().Select(x => x.ToString()));
}

I put in the Github for future reference.

If the information is not what you want, the problem is different from what is in the question and a new one should be asked. I answered what solves what was asked.

  • I am wanting that router ip. Ex: 192.168.0.1(this is mine)

  • It looks like it gives the mask

Browser other questions tagged

You are not signed in. Login or sign up in order to post.