使用C#替换IP v4的最后一个八位字节

时间:2013-09-29 11:28:32

标签: c# ipv4

我想将IP v4的最后一个八位字节替换为另一个新的八位字节。

例如,如果我的IP v4以下:

192.168.0.100

我希望最后一个八位字节为200:

192.168.0.200

使用Linq或正则表达式执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

更新的答案:

试试吧......

        var bytes = IPAddress.Parse("192.168.1.33").GetAddressBytes();
        // set the value here
        bytes[3] = 100;

        IPAddress ipAddress = new IPAddress(bytes);

        var bytes = IPAddress.Parse("192.168.1.33").GetAddressBytes(); 
        // set the value here
        bytes[3] = 100;

        System.Text.StringBuilder ipAddress = new System.Text.StringBuilder();
        foreach (byte b in bytes)
        {
            ipAddress.AppendFormat("{0}.", b);
        }

       string ipAddress1 = ipAddress.ToString();
       ipAddress1 = ipAddress1.TrimEnd('.');

       var newIp = IPAddress.Parse(ipAddress1);