Divide the IP address into four separate values

How to split an IP address into four separate values?

Example if my ip is 192.168.0.1

Value1 = 192

Value2 = 168

Value 3 = 0

Value 4 = 1

+4
source share
5 answers

If you just need different parts, you can use

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

You must check the IP address before this.

+6
source

For IPv4, each octet is one byte. You can use System.Net.IPAddress to parse the address and capture an array of bytes, for example:

 // 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); } 

Code Result:

 192 168 0 1 
+8
source

I would just call .ToString() and then .Split('.'); .

+2
source

You can get them as an array of integers, for example:

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

Good luck

+1
source
 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 
0
source

Source: https://habr.com/ru/post/1334780/


All Articles