Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get unused IP address

Tags:

c#

networking

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#?

like image 669
Amjad Abdelrahman Avatar asked Mar 22 '23 02:03

Amjad Abdelrahman


1 Answers

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

like image 165
sino Avatar answered Apr 04 '23 23:04

sino