Convert an IPAddress to string

1

This code gets the default gateway , but I can not convert the result to string and put it in 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...
}
    
asked by anonymous 24.06.2016 / 02:24

2 answers

1

This property is deprecated. Use the GetAddressBytes() method that will return an array of bytes with each part of the IP. Then just give 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()));
}

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

    
24.06.2016 / 03:09
0

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

    
24.06.2016 / 21:10