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 =开发者_StackOverflow中文版 0
Value4 = 1
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.
I would simply call .ToString()
and then .Split('.');
.
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
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();
Good luck!
精彩评论