简体   繁体   中英

get unused IP address

I need to get an available IP from the DHCP. I tried to get any ip address and start to ping the next until I reach one that doesn't respond.

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;
        }
    }
}

However, sometimes the DHCP reserves special address for some computers, so I need to get an available ip address from the dhcp. How can I implement that in C#?

That is not the right way you are using it , you should request the DHCP server a new ip and then accept it , read about communicating with DHCP Server here

http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol

A client application cannot make a request to the DHCP server for all available addresses.

A DHCP server can only process the following messages from a client:

  • DHCPDISCOVER
  • DHCPREQUEST
  • DHCPDECLINE
  • DHCPRELEASE
  • DHCPINFORM

Please see RFC 2131 - Dynamic Host Configuration Protocol for additional information.

If you are running Windows DHCP server and you have access to the box, you can use Windows PowerShell Scripting to query the DHCP database.

Excerpt from Weekend Scripter: Parsing the DHCP Database? No Way!

  • Summary: Microsoft Scripting Guy, Ed Wilson, talks about a Windows PowerShell function from the DHCPServer module that permits parsing the DHCP database.

我发现这个应用程序解决了这个问题http://www.centrel-solutions.com/support/tools.aspx?feature=dhcpapi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM