获取当前使用的网络适配器

获取当前使用的网络适配器

本文介绍了获取当前使用的网络适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取当前使用的网络适配器.例如,如果我在ASP.NET Core中收到一个Web请求,我想知道正在使用哪个适配器来处理该请求.

I'm trying to fetch the currently used network adapter.For example, if I'm receiving a web request in ASP.NET Core, I want to know which adapter is being used to handle that request.

谢谢!

推荐答案

您可以使用 HttpContext.Connection.LocalIpAddress属性以获取连接的本地(服务器)端的IP地址,然后找到 NetworkInterface 实例,该实例绑定了相同的地址.

You can use the HttpContext.Connection.LocalIpAddress property to get the IP address of the local (server) end of the connection, then find the NetworkInterface instance that has the same address bound to it.

using System.Linq;
using System.Net.NetworkInformation;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult GetInterfaceInfo()
        {
            var connectionLocalAddress = HttpContext.Connection.LocalIpAddress;
            var connectionLocalInterface = NetworkInterface.GetAllNetworkInterfaces()
                .Where(iface => iface.GetIPProperties().UnicastAddresses.Any(unicastInfo => unicastInfo.Address.Equals(connectionLocalAddress)))
                .SingleOrDefault();
            var results = new {
                NetworkInterface = connectionLocalInterface,
                IPInterfaceProperties = connectionLocalInterface?.GetIPProperties(),
                IPInterfaceStatistics = connectionLocalInterface?.GetIPStatistics(),
                IPv4InterfaceStatistics = connectionLocalInterface?.GetIPv4Statistics()
            };

            return Json(
                results,
                new JsonSerializerSettings() {
                    ContractResolver = new IgnorePropertyExceptionsResolver(),
                    Formatting = Formatting.Indented
                }
            );
        }
    }
}

访问http://localhost:12345/Home/GetInterfaceInfo然后会产生...

Accessing http://localhost:12345/Home/GetInterfaceInfo then produces...

{
    "NetworkInterface": {
        "Id": "{01234567-ABCD-EF01-2345-6789ABCDEF01}",
        "Name": "Loopback Pseudo-Interface 1",
        "Description": "Software Loopback Interface 1",
        "NetworkInterfaceType": 24,
        "OperationalStatus": 1,
        "Speed": 1073741824,
        "IsReceiveOnly": false,
        "SupportsMulticast": true
    },
    "IPInterfaceProperties": {
        "IsDnsEnabled": false,
        "IsDynamicDnsEnabled": true,
        "DnsSuffix": "",
        "AnycastAddresses": [],
        "UnicastAddresses": [
            {
                "Address": {
                    "AddressFamily": 23,
                    "ScopeId": 0,
                    "IsIPv6Multicast": false,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false
                },
                "IPv4Mask": {
                    "AddressFamily": 2,
                    "IsIPv6Multicast": false,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false,
                    "Address": 0
                },
                "PrefixLength": 128,
                "IsTransient": false,
                "IsDnsEligible": false,
                "PrefixOrigin": 2,
                "SuffixOrigin": 2,
                "DuplicateAddressDetectionState": 4,
                "AddressValidLifetime": 4294967295,
                "AddressPreferredLifetime": 4294967295,
                "DhcpLeaseLifetime": 1542939
            },
            {
                "Address": {
                    "AddressFamily": 2,
                    "IsIPv6Multicast": false,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false,
                    "Address": 16777343
                },
                "IPv4Mask": {
                    "AddressFamily": 2,
                    "IsIPv6Multicast": false,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false,
                    "Address": 255
                },
                "PrefixLength": 8,
                "IsTransient": false,
                "IsDnsEligible": false,
                "PrefixOrigin": 2,
                "SuffixOrigin": 2,
                "DuplicateAddressDetectionState": 4,
                "AddressValidLifetime": 4294967295,
                "AddressPreferredLifetime": 4294967295,
                "DhcpLeaseLifetime": 1542939
            }
        ],
        "MulticastAddresses": [
            {
                "Address": {
                    "AddressFamily": 23,
                    "ScopeId": 1,
                    "IsIPv6Multicast": true,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false
                },
                "IsTransient": false,
                "IsDnsEligible": false,
                "PrefixOrigin": 0,
                "SuffixOrigin": 0,
                "DuplicateAddressDetectionState": 0,
                "AddressValidLifetime": 0,
                "AddressPreferredLifetime": 0,
                "DhcpLeaseLifetime": 0
            },
            {
                "Address": {
                    "AddressFamily": 2,
                    "IsIPv6Multicast": false,
                    "IsIPv6LinkLocal": false,
                    "IsIPv6SiteLocal": false,
                    "IsIPv6Teredo": false,
                    "IsIPv4MappedToIPv6": false,
                    "Address": 4211081199
                },
                "IsTransient": false,
                "IsDnsEligible": false,
                "PrefixOrigin": 0,
                "SuffixOrigin": 0,
                "DuplicateAddressDetectionState": 0,
                "AddressValidLifetime": 0,
                "AddressPreferredLifetime": 0,
                "DhcpLeaseLifetime": 0
            }
        ],
        "DnsAddresses": [
            {
                "AddressFamily": 23,
                "ScopeId": 1,
                "IsIPv6Multicast": false,
                "IsIPv6LinkLocal": false,
                "IsIPv6SiteLocal": true,
                "IsIPv6Teredo": false,
                "IsIPv4MappedToIPv6": false
            },
            {
                "AddressFamily": 23,
                "ScopeId": 1,
                "IsIPv6Multicast": false,
                "IsIPv6LinkLocal": false,
                "IsIPv6SiteLocal": true,
                "IsIPv6Teredo": false,
                "IsIPv4MappedToIPv6": false
            },
            {
                "AddressFamily": 23,
                "ScopeId": 1,
                "IsIPv6Multicast": false,
                "IsIPv6LinkLocal": false,
                "IsIPv6SiteLocal": true,
                "IsIPv6Teredo": false,
                "IsIPv4MappedToIPv6": false
            }
        ],
        "GatewayAddresses": [],
        "DhcpServerAddresses": [],
        "WinsServersAddresses": []
    },
    "IPInterfaceStatistics": {
        "OutputQueueLength": 0,
        "BytesSent": 0,
        "BytesReceived": 0,
        "UnicastPacketsSent": 0,
        "UnicastPacketsReceived": 0,
        "NonUnicastPacketsSent": 0,
        "NonUnicastPacketsReceived": 0,
        "IncomingPacketsDiscarded": 0,
        "OutgoingPacketsDiscarded": 0,
        "IncomingPacketsWithErrors": 0,
        "OutgoingPacketsWithErrors": 0,
        "IncomingUnknownProtocolPackets": 0
    },
    "IPv4InterfaceStatistics": {
        "OutputQueueLength": 0,
        "BytesSent": 0,
        "BytesReceived": 0,
        "UnicastPacketsSent": 0,
        "UnicastPacketsReceived": 0,
        "NonUnicastPacketsSent": 0,
        "NonUnicastPacketsReceived": 0,
        "IncomingPacketsDiscarded": 0,
        "OutgoingPacketsDiscarded": 0,
        "IncomingPacketsWithErrors": 0,
        "OutgoingPacketsWithErrors": 0,
        "IncomingUnknownProtocolPackets": 0
    }
}

IgnorePropertyExceptionsResolver类来自忽略在序列化为JSON时引发异常的类成员,如下所示.

The IgnorePropertyExceptionsResolver class comes from Ignoring class members that throw exceptions when serializing to JSON and looks like this...

using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace WebApplication1.Controllers
{
    internal class IgnorePropertyExceptionsResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var jsonProperty = base.CreateProperty(member, memberSerialization);

            jsonProperty.ShouldSerialize = instance => {
                try
                {
                    var instanceProperty = (PropertyInfo) member;

                    if (instanceProperty.CanRead)
                    {
                        instanceProperty.GetValue(instance, null);

                        return true;
                    }
                }
                catch
                {
                }

                return false;
            };

            return jsonProperty;
        }
    }
}

之所以使用此类,是因为访问results.IPInterfaceProperties的collection属性中的某些IPAddress对象会在访问其Address属性时引发异常,因此解析程序仅忽略了有问题的属性,以使输出工作.当然,您将直接访问这些对象,而不是先将它们转换为JSON,因此该演示代码只真正需要该类.

The reason I use this class is because some of the IPAddress objects within the collection properties of results.IPInterfaceProperties would throw an exception when their Address property was accessed, so that resolver just omits the offending properties to make the output work. Of course, you would be accessing these objects directly and not converting them to JSON first, so that class is only really needed for this demo code.

这篇关于获取当前使用的网络适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 21:54