将IP地址拆分为四个单独的值

时间:2011-01-08 22:07:11

标签: c# string

如何将IP地址拆分为四个单独的值?

示例如果我的IP是192.168.0.1

Value1 = 192

Value2 = 168

Value3 = 0

Value4 = 1

5 个答案:

答案 0 :(得分:9)

对于IPv4,每个八位字节是一个字节。您可以使用System.Net.IPAddress来解析地址并获取字节数组,如下所示:

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

代码的结果是:

192
168
0
1

答案 1 :(得分:6)

如果您只想要不同的部分,那么您可以使用

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

您应该在此之前验证IP地址。

答案 2 :(得分:2)

我只需拨打.ToString(),然后拨打.Split('.');

答案 3 :(得分:1)

您可以将它们作为整数数组获取,如下所示:

int [] tokens = "192.168.0.1".Split('.').Select(p => Convert.ToInt32(p)).ToArray();
祝你好运!

答案 4 :(得分:0)

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
相关问题