1

I have an application on Windows CE 5.0 and Windows Mobile 5.0 where I am currently fetching the IP address using the following code:

IPHostEntry dnsEntry = Dns.GetHostEntry(_host);
foreach (IPAddress ia in dnsEntry.AddressList)
{
    if (ia.AddressFamily == AddressFamily.InterNetwork)
    {
        _address = ia;  
        break;
    }
}

where "_host" is the hostname that is fetched from an XML config file. My question now is how do I see the remaining lease time for the IP address "_address"?

Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
Nethakaaru
  • 25
  • 4

2 Answers2

1

I'm leaving the previous answer as it may be useful for somebody else, but I think it's possible on Windows CE 5.0, using IP Helper API.

First, take a look at Managing Network Adapters (Windows CE 5.0).

You'll use the GetAdaptersInfo function.

It returns an IP_ADAPTER_INFO structure, that has an LeaseExpires property.

Don't know if you ever used Windows API on C# before. It's a little ugly but you get used to it, and as long as it works, it's fine! =D

PInvoke.NET has a good example on how to use it. Don't know if it's related to the desktop or CE version, but I think you can manage to make it work.

It would be something like:

[DllImport("iphlpapi.dll", CharSet=CharSet.Ansi)]
public static extern int GetAdaptersInfo(IntPtr pAdapterInfo, ref Int64 pBufOutLen);

const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
const int ERROR_BUFFER_OVERFLOW = 111;
const int MAX_ADAPTER_NAME_LENGTH = 256;
const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
const int MIB_IF_TYPE_OTHER = 1;
const int MIB_IF_TYPE_ETHERNET = 6;
const int MIB_IF_TYPE_TOKENRING = 9;
const int MIB_IF_TYPE_FDDI = 15;
const int MIB_IF_TYPE_PPP = 23;
const int MIB_IF_TYPE_LOOPBACK = 24;
const int MIB_IF_TYPE_SLIP = 28;

public static void GetAdapters()
{
   long structSize = Marshal.SizeOf( typeof( IP_ADAPTER_INFO ) );
   IntPtr pArray = Marshal.AllocHGlobal( new IntPtr(structSize) );

   int ret = GetAdaptersInfo( pArray, ref structSize );

   if (ret == ERROR_BUFFER_OVERFLOW ) // ERROR_BUFFER_OVERFLOW == 111
   {
     // Buffer was too small, reallocate the correct size for the buffer.
     pArray = Marshal.ReAllocHGlobal( pArray, new IntPtr (structSize) );

     ret = GetAdaptersInfo( pArray, ref structSize );
   } // if

   if ( ret == 0 )
   {
     // Call Succeeded
     IntPtr pEntry = pArray;

     do
     {
       // Retrieve the adapter info from the memory address
       IP_ADAPTER_INFO entry = (IP_ADAPTER_INFO)Marshal.PtrToStructure( pEntry, typeof( IP_ADAPTER_INFO ));

       // ***Do something with the data HERE!***
       Console.WriteLine("\n");
       Console.WriteLine( "Index: {0}", entry.Index.ToString() );

       // Adapter Type
       string tmpString = string.Empty;
       switch( entry.Type )
       {
         case MIB_IF_TYPE_ETHERNET  : tmpString = "Ethernet";  break;
         case MIB_IF_TYPE_TOKENRING : tmpString = "Token Ring"; break;
         case MIB_IF_TYPE_FDDI      : tmpString = "FDDI"; break;
         case MIB_IF_TYPE_PPP       : tmpString = "PPP"; break;
         case MIB_IF_TYPE_LOOPBACK  : tmpString = "Loopback"; break;
         case MIB_IF_TYPE_SLIP      : tmpString = "Slip"; break;
         default                    : tmpString = "Other/Unknown"; break;
       } // switch
       Console.WriteLine( "Adapter Type: {0}", tmpString );

       Console.WriteLine( "Name: {0}", entry.AdapterName );
       Console.WriteLine( "Desc: {0}\n", entry.AdapterDescription );

       Console.WriteLine( "DHCP Enabled: {0}", ( entry.DhcpEnabled == 1 ) ? "Yes" : "No" );

       if (entry.DhcpEnabled == 1)
       {
         Console.WriteLine( "DHCP Server : {0}", entry.DhcpServer.IpAddress.Address );

         // Lease Obtained (convert from "time_t" to C# DateTime)
         DateTime pdatDate = new DateTime(1970, 1, 1).AddSeconds( entry.LeaseObtained ).ToLocalTime();
         Console.WriteLine( "Lease Obtained: {0}", pdatDate.ToString() );

         // Lease Expires (convert from "time_t" to C# DateTime)
         pdatDate = new DateTime(1970, 1, 1).AddSeconds( entry.LeaseExpires ).ToLocalTime();
         Console.WriteLine( "Lease Expires : {0}\n", pdatDate.ToString() );
       } // if DhcpEnabled

       Console.WriteLine( "IP Address     : {0}", entry.IpAddressList.IpAddress.Address );
       Console.WriteLine( "Subnet Mask    : {0}", entry.IpAddressList.IpMask.Address );
       Console.WriteLine( "Default Gateway: {0}", entry.GatewayList.IpAddress.Address );

       // MAC Address (data is in a byte[])
       tmpString = string.Empty;
       for (int i = 0; i < entry.AddressLength - 1; i++)
       {
         tmpString += string.Format("{0:X2}-", entry.Address[i]);
       }
       Console.WriteLine( "MAC Address    : {0}{1:X2}\n", tmpString, entry.Address[entry.AddressLength - 1] );

       Console.WriteLine( "Has WINS: {0}", entry.HaveWins ? "Yes" : "No" );
       if (entry.HaveWins)
       {
         Console.WriteLine( "Primary WINS Server  : {0}", entry.PrimaryWinsServer.IpAddress.Address );
         Console.WriteLine( "Secondary WINS Server: {0}", entry.SecondaryWinsServer.IpAddress.Address );
       } // HaveWins

       // Get next adapter (if any)
       pEntry = entry.Next;

     }
     while( pEntry != IntPtr.Zero );

     Marshal.FreeHGlobal(pArray);

   } // if
   else
   {
     Marshal.FreeHGlobal(pArray);
     throw new InvalidOperationException( "GetAdaptersInfo failed: " + ret );
   }

} // GetAdapters
Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
0

Never tried this before, but I think you are looking for UnicastIPAddressInformation.DhcpLeaseLifetime property.

Take a look at this example from MSDN:

public static void DisplayUnicastAddresses()
{
    Console.WriteLine("Unicast Addresses");
    NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface adapter in adapters)
    {
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses;
        if (uniCast.Count >0)
        {
            Console.WriteLine(adapter.Description);
            string lifeTimeFormat = "dddd, MMMM dd, yyyy  hh:mm:ss tt";
            foreach (UnicastIPAddressInformation uni in uniCast)
            {
                DateTime when;

                Console.WriteLine("  Unicast Address ......................... : {0}", uni.Address);
                Console.WriteLine("     Prefix Origin ........................ : {0}", uni.PrefixOrigin);
                Console.WriteLine("     Suffix Origin ........................ : {0}", uni.SuffixOrigin);
                Console.WriteLine("     Duplicate Address Detection .......... : {0}", 
                    uni.DuplicateAddressDetectionState);

                // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM
                // if en-us is the current culture.

                // Calculate the date and time at the end of the lifetimes.    
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime);
                when = when.ToLocalTime();    
                Console.WriteLine("     Valid Life Time ...................... : {0}", 
                    when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture)
                );
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime);   
                when = when.ToLocalTime();
                Console.WriteLine("     Preferred life time .................. : {0}", 
                    when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture)
                ); 

                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime);
                when = when.ToLocalTime(); 
                Console.WriteLine("     DHCP Leased Life Time ................ : {0}", 
                    when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture)
                );
            }
            Console.WriteLine();
        }
    }
}
Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
  • I was actually looking at that for quite a while. I couldn't get the reference right and ended up finding a thread that claims System.Net.NetworkInformation is not supported in Windows Mobile. – Nethakaaru Jul 20 '17 at 14:15
  • Did you see this post? [Getting Network Adapter Information in Windows Mobile](http://www.devlper.com/2008/09/getting-network-adapter-information-in-windows-mobile/) – Anderson Pimentel Jul 20 '17 at 14:36
  • I assume this property is not supported on Compact Framework. – josef Jul 21 '17 at 05:15
  • @AndersonPimentel Including your link there seems to be ways to manage IP leases in CE using C++. https://msdn.microsoft.com/en-us/library/aa450427.aspx . Maybe the best approach would be to make a .dll? – Nethakaaru Jul 21 '17 at 06:23
  • Even when looking at C++ the closest thing I can find is renewing the lease, not fetch the time. I would like to avoid C++ if possible. Never used it. – Nethakaaru Jul 21 '17 at 07:19