c# - 从 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);
}
解决方案
使用此答案生成下一个 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));
}
当然,您可以在链接问题中使用任何其他方法,甚至可以使用字符串替换。
推荐阅读
- abp - 在 abp 框架 Web 应用程序中使用 Azure B2C 作为主要身份验证提供程序
- git - 将包含所有分支的 git 项目导入 GitLab
- hdl - SystemVerilog:使用流式操作符打包然后解包会给出错误:Vivado 中的“解包数组连接中的元素类型错误”
- windows - 批处理文件映射网络驱动器
- xml - 如何使 DITA catalog.xml 在 VS Code 中工作?
- javascript - 如何从 GeoJSON 文件中总结重叠线要素的属性值?
- angular - 如何使用 Angular 10 中的 Spring Boot Post Web 服务解析/下载多个文件
- javascript - 为什么这个 createAsyncThunk 行为异常?
- bash - 使用 goa-webFramework 从 Go 执行 bash 脚本 / 命令未执行
- javascript - 如何在不删除 react index.js 文件中的严格模式的情况下解决严格模式警告