The following code should remedy the above issue for the Netduino Plus 2 and will still work for the Netduino 3 (Ethernet and Wifi) boards. Short summary: specify a timeout in milliseconds and loop until the DHCP address has been assigned.
/// <summary>
/// Returns the IP address of the device.
/// </summary>
public NetworkInformation GetNetworkDetails(int interfaceIndex)
{
NetworkInformation information = null;
// Set up event handlers for network state changes.
NetworkChange.NetworkAvailabilityChanged += OnInternalNetworkAvailabilityChanged;
NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
try
{
// Wait for the network to become available and for a DHCP address to be allocated.
bool isWaitingToInitialise = true;
while (isWaitingToInitialise)
{
var isSignalled = WaitHandle.WaitAll(new[] { m_WaitForAddressChange, m_WaitForNetwork }, m_WaitForNetworkEventInMilliseconds, false);
if (!isSignalled)
{
// Retrieve network interface details to see if the initialisation had already occurred.
information = QueryInterface(interfaceIndex);
if ((information.IsDHCPEnabled) && (information.IpAddress != "0.0.0.0"))
{
isWaitingToInitialise = false;
}
}
else isWaitingToInitialise = false;
}
information = QueryInterface(interfaceIndex);
}
finally
{
m_WaitForAddressChange.Reset();
m_WaitForNetwork.Reset();
}
return information;
}
/// <summary>
/// Queries a network device for details about its connection state.
/// </summary>
/// <param name="interfaceIndex">
/// The index of the device to query.
/// </param>
/// <returns>
/// The status information on the network device.
/// </returns>
public NetworkInformation QueryInterface(int interfaceIndex)
{
NetworkInformation information = null;
var networkInterface = GetInterface(interfaceIndex);
if (networkInterface != null)
{
// Then capture the network details.
information = new NetworkInformation();
information.IpAddress = networkInterface.IPAddress;
information.IsDHCPEnabled = networkInterface.IsDhcpEnabled;
information.SubnetMask = networkInterface.SubnetMask;
information.MacAddress = networkInterface.PhysicalAddress;
information.NetworkInterfaceType = networkInterface.NetworkInterfaceType.ToString();
}
return information;
}