Divida una dirección IP en cuatro valores separados

How do I split an IP address into four separate values?

Ejemplo if my ip is 192.168.0.1

Value1 = 192

Value2 = 168

Value3 = 0

Value4 = 1

preguntado el 08 de enero de 11 a las 22:01

What's your input - string / System.Net.IPAddress? Would you like the output as strings / bytes / int32s ...? -

By spending one or two seconds familiarizing yourself with the .NET documentation. Or are you too lazy to bother? System.Net.IPAddress.GetAddressBytes might work. -

5 Respuestas

If you just want the different parts then you can use

        string ip = "192.168.0.1";
        string[] values = ip.Split('.');

You should validate the IP address before that though.

Respondido el 09 de enero de 11 a las 01:01

For IPv4, each octet is one byte. You can use System.Net.IPAddress to parse the address and grab the array of bytes, like this:

// parse the address
IPAddress ip = IPAddress.Parse("192.168.0.1");

//iterate the byte[] and print each byte
foreach(byte i in ip.GetAddressBytes())
{
    Console.WriteLine(i);
}

The result of the code is:

192
168
0
1

Respondido el 09 de enero de 11 a las 01:01

I would simply call .ToString() y entonces .Split('.');.

Respondido el 09 de enero de 11 a las 01:01

string ip = "192.168.0.1";
string[] tokens = ip.Split('.');
int value1 = Int32.Parse(tokens[0]);   // 192
int value2 = Int32.Parse(tokens[1]);   // 168
int value3 = Int32.Parse(tokens[2]);   // 0
int value4 = Int32.Parse(tokens[3]);   // 1

Respondido el 09 de enero de 11 a las 01:01

You can get them as an array of integer like the following:

int [] tokens = "192.168.0.1".Split('.').Select(p => Convert.ToInt32(p)).ToArray();

¡Buena suerte!

Respondido el 09 de enero de 11 a las 01:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.