首页 > 解决方案 > 从 IP 数最后一位数

问题描述

我正在购买 IP 并尝试使用提供商提供的 API 创建虚拟 Mac。

我的想法是您将输入起始 IP,然后输入您拥有的 IP 数量。它们总是一样的,只有最后一个数字上升一个。

例如

51.82.125.14
51.82.125.15
51.82.125.16
...
...

然后在您输入第一个 IP 和 IP 数量后,它将通过一个看起来像这样的 for 循环:

int MAX = count.Length;
for(int i = 0; i < MAX; i++)
{
                 
}

并在那里以某种方式计算ip的最后一位数字并将其放入我初始化的列表中:

List<string> ipList = new List<string>();

在 for 循环完成后,所有 ips 都应该在列表中,并且应该开始创建虚拟 mac 的过程。

但是我如何计算IP的最后一位数字,我应该确定为字符串还是其他?

谢谢你

编辑

我实际上已经尝试过这个解决方案,但它只吐出 1 个增量,例如输入 ip "192.168.0.1" 并计数 "6" 它打印 6x 192.168.0.2

int MAX = int.Parse(count);
for (int i = 0; i < MAX; i++)
{
   int lastIndex = ip.LastIndexOf(".");
   string lastNumber = ip.Substring(lastIndex + 1);
   string increment = (int.Parse(lastNumber) + 1).ToString();
   string result = string.Concat(ip.Substring(0, lastIndex + 1), increment);
   Notify(result);
}

标签: c#ip

解决方案


使用此答案生成下一个 IPv4 地址。

private string GetIpV4Address(string ipAddress, int increment)
{
    var addressBytes = IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray();
    var ipAsUint = BitConverter.ToUInt32(addressBytes, 0);
    var nextAddress = BitConverter.GetBytes(ipAsUint + increment);
    return string.Join(".", nextAddress.Reverse().Skip(4));
}

创建下一个count地址的列表。

 private IEnumerable<string> GetConsecutiveIpV4Addresses(string ipAddress, int count)
 {
     for (var i = 0; i <= count; i++)
         yield return GetIpV4Address(ipAddress, i);
 }

你可以像这样在你的代码中使用它。

private void DoSomething()
{
    // ...your code
    ipList.AddRange(GetConsecutiveIpV4Addresses(ipAddress, count));
}

当然,您可以在链接问题中使用任何其他方法,甚至可以使用字符串替换。


推荐阅读