dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.03k stars 4.68k forks source link

[API Proposal]: Add `DhcpLeaseExpires` and `DhcpLeaseObtained` to IPv4InterfaceProperties #107659

Open ode2code95 opened 2 weeks ago

ode2code95 commented 2 weeks ago

Background and motivation

We should be able to easily retrieve all of the properties displayed with ipconfig /all with the classes in the System.Net.NetworkInformation namespace:
CleanShot 2024-09-10 at 18 42 16@2x
The IPv4InterfaceProperties class in System.Net.NetworkInformation yields a number of the IPv4 metrics for network adapters. It includes IsDhcpEnabled but not the DhcpLeaseExpires or the DhcpLeaseObtained properties from WMI. The current workaround is to query WMI directly using the Win32_NetworkAdapterConfiguration class.

API Proposal

namespace System.Net.NetworkInformation;

// src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPv4InterfaceProperties.cs
public class IPv4InterfaceProperties
{
    // ... add these two properties:
    public DateTime DhcpLeaseExpires { get; }
    public DateTime DhcpLeaseObtained { get; }
}

API Usage

// Print the DHCP lease origin and expiration for each network interface:
foreach (var ifc in NetworkInterface.GetAllNetworkInterfaces())
{
    var ipv4Props = ifc.GetIPProperties().GetIPv4Properties();
    Console.WriteLine($"Name: {ifc.Name}");
    Console.WriteLine($"DHCP Lease Obtained: {ipv4Props.DhcpLeaseObtained}");
    Console.WriteLine($"DHCP Lease Expires: {ipv4Props.DhcpLeaseExpires}");
}

Alternative Designs

Perhaps an IPAddress instance has better access to these properties?

Risks

None that I can see. We are already querying WMI for other properties from the Win32_NetworkAdapterConfiguration class.

dotnet-policy-service[bot] commented 2 weeks ago

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.

wfurt commented 2 weeks ago

this may be difficult to get it working on all platforms as the info may be proprietary to given implementation.

ode2code95 commented 2 weeks ago

I did just discover this afternoon another workaround using the UnicastIPAddressInformation.DhcpLeaseLifetime property. Somehow I had missed this one yesterday. This is the number of seconds until lease expiration, and we can calculate the DateTime from that if we want it.

This property is annotated as Windows-specific.

I have not tested it yet, but I'm assuming if we read this property on the interface's IPv4 address we should get the answer we are looking for. I'll admit that I do not understand DHCP with regards to IPv6 yet.