Tim*_*Tim 5 .net c# networking ip-address
在本地适配器子网上查找下一个未使用的IP地址的最简单方法是什么?
IPAddress GetNextFreeIP(NetworkInterface intface)
{
...?
}
Run Code Online (Sandbox Code Playgroud)
更新
我编写了一个BOOTP/TFTP服务器,可用于许多不同的场景(交叉电缆,小型专用网络,大型企业网络).我必须给小型嵌入式系统我正在更新一个IP地址,并希望找到一个备用的系统供它使用......
当您说无法确保 IP 不被使用时,您在技术上是正确的。但我现在决定依靠这个......
public static IPAddress FindNextFree(this IPAddress address)
{
IPAddress workingAddress = address;
Ping pingSender = new Ping();
while (true)
{
byte[] localBytes = workingAddress.GetAddressBytes();
localBytes[3]++;
if (localBytes[3] > 254)
localBytes[3] = 1;
workingAddress = new IPAddress(localBytes);
if (workingAddress.Equals(address))
throw new TimeoutException("Could not find free IP address");
PingReply reply = pingSender.Send(workingAddress, 1000);
if (reply.Status != IPStatus.Success)
{
return workingAddress;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4024 次 |
| 最近记录: |