从 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 循环完成后,所有 IP 都应该在列表中,并且应该开始创建虚拟 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);
}

使用此答案生成下一个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));
}

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

您的代码不会返回所需的输出,因为您在循环中获得相同的最后一个字节并将其增加 1 从而创建相同的 IP192.168.0.2

string lastNumber = ip.Substring(lastIndex + 1);

要使其工作,请获取循环之前的最后一个字节,并在其中将其增加 1。

例如:

var MAX = 16;
var ip = "192.168.0.1";
if (!IPAddress.TryParse(ip, out IPAddress ipa))
return;
var ipBytes = ipa.GetAddressBytes();
var lastByte = ipBytes.Last();

for (int i = 0; i < MAX; i++)
{
var result = string.Join(".", ipBytes.Take(3).Append(lastByte));
lastByte += 1; //Move this up if you want to start with 192.168.0.2
Notify(result);
}

或者,创建一个返回 IP 地址范围的函数:

public static IEnumerable<string> CreateIPRange(string ip, int count)
{
if (!IPAddress.TryParse(ip, out IPAddress ipa))
return Enumerable.Empty<string>();
var ipBytes = ipa.GetAddressBytes();
return Enumerable.Range(0, count)
.Select(i => string
.Join(".", ipBytes.Take(3)
.Append((byte)(ipBytes.Last() + i))));
}

。或返回IEnumerable<IPAddress>

public static IEnumerable<IPAddress> CreateIPARange(string ip, int count)
{
if (!IPAddress.TryParse(ip, out IPAddress ipa))
return Enumerable.Empty<IPAddress>();
var ipBytes = ipa.GetAddressBytes();
return Enumerable.Range(0, count)
.Select(i => new IPAddress(ipBytes.Take(3)
.Append((byte)(ipBytes.Last() + i))
.ToArray()));
}

。并按如下方式调用它:

void TheCaller()
{
var MAX = 16;
var ip = "192.168.0.1";
CreateIPARange(ip, MAX).ToList().ForEach(x => Console.WriteLine(x));
}

最新更新