How do I split an IP address into four separate values?
Example if my ip is 192.168.0.1
Value1 = 192
Value2 = 168
Value3 = 0
Value4 = 1
IPv4 addresses are usually represented in dot-decimal notation, consisting of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 192.0. 2.1. Each part represents a group of 8 bits (an octet) of the address.
The reason for dividing it into four sections is to identify the Class of the network. This helps to break your IP address into binary form and locate your device to transmit and receive data from the internet.
A subnet mask is used to divide an IP address into two parts. One part identifies the host (computer), the other part identifies the network to which it belongs.
An IP Address is shown as 4 decimal numbers representing 4 bytes: d.d.d.d where d = decimal number (0 - 255). High order bits are the network identifier and lower order bits are the host identifier.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With