Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an IP address into four separate values

Tags:

string

c#

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

like image 223
001 Avatar asked Jan 08 '11 22:01

001


People also ask

Can an IP address have 4 numbers?

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.

Why IP address is divided into 4 parts?

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.

How do you split an IP address?

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.

What are the 4 numbers after IP address?

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.


2 Answers

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
like image 171
arcain Avatar answered Oct 01 '22 09:10

arcain


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.

like image 31
BrokenGlass Avatar answered Oct 01 '22 09:10

BrokenGlass