我需要从 DHCP 获取可用的 IP。我试图获取任何 IP 地址并开始 ping 下一个地址,直到我到达一个没有响应的地址。
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;
}
}
}
但是,有时 DHCP 会为某些计算机保留特殊地址,因此我需要从 dhcp 获取可用的 IP 地址。如何在 C# 中实现它?