使用IP地址获取租约时间

时间:2017-07-20 14:02:58

标签: c# .net windows-ce dhcp windows-mobile-5.0

我在Windows CE 5.0和Windows Mobile 5.0上有一个应用程序,我目前使用以下代码获取IP地址:

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

其中" _host"是从XML配置文件中获取的主机名。我现在的问题是如何查看IP地址的剩余租用时间" _address"?

2 个答案:

答案 0 :(得分:1)

我离开之前的答案,因为它可能对其他人有用,但我认为在Windows CE 5.0上可以使用IP Helper API。

首先,看看Managing Network Adapters (Windows CE 5.0)

您将使用GetAdaptersInfo功能。

它返回IP_ADAPTER_INFO结构,具有LeaseExpires属性。

不知道您以前是否曾在C#上使用过Windows API。它有点难看,但你已经习惯了,只要它有效,它就没事了! = d

PInvoke.NET有good example如何使用它。不知道它是否与桌面版或CE版相关,但我认为你可以设法让它工作。

这将是:

[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

答案 1 :(得分:0)

之前从未尝试过,但我认为您正在寻找UnicastIPAddressInformation.DhcpLeaseLifetime属性。

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