private static IPAddress RequestControlSystemEndpointAddress(string appID, NetworkInterface nic) { IPAddress address = null; DhcpRequestFailedException requestException = null; var thread = new Thread(() => { try { using (var client = new DhcpClient() { ApplicationID = appID }) { // get DHCP option data byte[] data = client.DhcpRequestParams(nic.Id, ControlSystemDhcpOptionID); if (data == null || data.Length <= 0) { requestException = new DhcpRequestFailedException("Empty DHCP option data returned"); return; } if (data.Length != 4) { requestException = new DhcpRequestFailedException("DHCP option data size is not valid"); return; } address = new IPAddress(data); } } catch (Exception e) { // We can catch all exceptions here and not re-throw because the caller knows how to handle a null return value. requestException = new DhcpRequestFailedException(e.Message); return; } }); thread.Start(); // wait no more than 3 minutes, to compensate for win7 bug 699003 (timezone issue // causing DHCP service to malfunction, leading to infinite blocking of DHCP API calls) if (thread.Join(TimeSpan.FromMinutes(3)) == false) { // Timed out waiting for DHCP response throw new DhcpRequestFailedException("Timed out while waiting for DHCP to respond"); } if (requestException != null) { throw requestException; } return(address); }
// This implementation is copied from the Windows GuestAgent implementation private static IPAddress GetDhcpAddress() { foreach (NetworkInterface nic in DhcpClient.GetDhcpInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } try { IPAddress address = RequestControlSystemEndpointAddress("WindowsAzureGuestAgent", nic); return(address); } catch (DhcpRequestFailedException e) { } } return(null); }