C# 检查 ip 地址是否与适配器 ip 地址设置匹配

发布于 2025-01-11 12:08:59 字数 1399 浏览 0 评论 0原文

我完全不熟悉 C#,因此在这里停留了一会儿。我从 https://stackoverflow.com/a/13175574 窃取了代码来读取电脑上所有可用的适配器设置。到目前为止,一切都很好。

我现在需要的是一种方法来检查哪些适配器能够连接到具有给定 IP 地址的连接设备。

我想要一个像“bool CheckIfValidIP(IPAddress适配器,IPAddress IPv4Mask,IPAddress地址)”这样的功能。

你能帮我一下吗?我知道这很简单:-/

编辑:

    public static class IPAddressExtensions
{
    public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
    {
        byte[] ipAdressBytes = address.GetAddressBytes();
        byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

        if (ipAdressBytes.Length != subnetMaskBytes.Length)
            throw new ArgumentException("Lengths of IP address and subnet mask do not match.");

        byte[] broadcastAddress = new byte[ipAdressBytes.Length];
        for (int i = 0; i < broadcastAddress.Length; i++)
        {
            broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
        }
        return new IPAddress(broadcastAddress);
    }

    public static bool IsInSameSubnet(IPAddress address2, IPAddress address, IPAddress subnetMask)
    {
        IPAddress network1 = address.GetNetworkAddress(subnetMask);
        IPAddress network2 = address2.GetNetworkAddress(subnetMask);

        return network1.Equals(network2);
    }
}

这段代码可以做到这一点。使用安全吗?

I'm totally out of C# hence hanging a little here. I stole the code from https://stackoverflow.com/a/13175574 to read out all adapter settings available on the pc. So far so good.

What I need now is a way to check, which of the adapters are able to connect to an attached device with a given ip address.

I'd like to have a function like "bool CheckIfValidIP(IPAddress adapter, IPAddress IPv4Mask, IPAddress address)".

Can you help me here? I know it's pretty trivial :-/

Edit:

    public static class IPAddressExtensions
{
    public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
    {
        byte[] ipAdressBytes = address.GetAddressBytes();
        byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

        if (ipAdressBytes.Length != subnetMaskBytes.Length)
            throw new ArgumentException("Lengths of IP address and subnet mask do not match.");

        byte[] broadcastAddress = new byte[ipAdressBytes.Length];
        for (int i = 0; i < broadcastAddress.Length; i++)
        {
            broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
        }
        return new IPAddress(broadcastAddress);
    }

    public static bool IsInSameSubnet(IPAddress address2, IPAddress address, IPAddress subnetMask)
    {
        IPAddress network1 = address.GetNetworkAddress(subnetMask);
        IPAddress network2 = address2.GetNetworkAddress(subnetMask);

        return network1.Equals(network2);
    }
}

This code shall do it. Is it safe to use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2025-01-18 12:08:59

一个非常简单的示例可以帮助您找到正确的方向,这是在 .Net core 6 中创建的:

using System.Net.NetworkInformation;
using System.Net.Sockets;

NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
var adaptertList = new List<NetworkInterface>();

const string IpAddressToValidate = "192.168.1.1"; //Both of these values can be retrieved from appsetting.json file
const string IpV4MaskToValidate = "255.255.255.0";

adaptertList = GetValidAdapterList(interfaces);

List<NetworkInterface> GetValidAdapterList(NetworkInterface[] interfaces) {
   var adaptertList = new List<NetworkInterface>();

   foreach (var adapter in interfaces) {
      var ipProps = adapter.GetIPProperties();

      foreach (var ip in ipProps.UnicastAddresses) {
         if ((adapter.OperationalStatus == OperationalStatus.Up)//Check for any conditions appropriate to your case
         && (ip.Address.AddressFamily == AddressFamily.InterNetwork)) {
            if (CheckIsValidIP(ip.Address.ToString(), ip.IPv4Mask.ToString(), IpAddressToValidate, IpV4MaskToValidate)) {
               adaptertList.Add(adapter);
               continue;//If IP found exit the loop, as the adapter is already added
            }
         }
      }
   }
   return adaptertList;
}

bool CheckIsValidIP(string ipAddress, string ipV4Mask, string validIpAddress, string validIpV4Mask) {
   return (ipAddress == validIpAddress && ipV4Mask == validIpV4Mask);
}

此代码将返回计算机中满足 Ip 地址和 ipv4mask 标准的所有适配器的列表。

A very simple example to get you in the right direction, this is created in .Net core 6:

using System.Net.NetworkInformation;
using System.Net.Sockets;

NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
var adaptertList = new List<NetworkInterface>();

const string IpAddressToValidate = "192.168.1.1"; //Both of these values can be retrieved from appsetting.json file
const string IpV4MaskToValidate = "255.255.255.0";

adaptertList = GetValidAdapterList(interfaces);

List<NetworkInterface> GetValidAdapterList(NetworkInterface[] interfaces) {
   var adaptertList = new List<NetworkInterface>();

   foreach (var adapter in interfaces) {
      var ipProps = adapter.GetIPProperties();

      foreach (var ip in ipProps.UnicastAddresses) {
         if ((adapter.OperationalStatus == OperationalStatus.Up)//Check for any conditions appropriate to your case
         && (ip.Address.AddressFamily == AddressFamily.InterNetwork)) {
            if (CheckIsValidIP(ip.Address.ToString(), ip.IPv4Mask.ToString(), IpAddressToValidate, IpV4MaskToValidate)) {
               adaptertList.Add(adapter);
               continue;//If IP found exit the loop, as the adapter is already added
            }
         }
      }
   }
   return adaptertList;
}

bool CheckIsValidIP(string ipAddress, string ipV4Mask, string validIpAddress, string validIpV4Mask) {
   return (ipAddress == validIpAddress && ipV4Mask == validIpV4Mask);
}

This code will return a list of all the adapter in the machine that meet the Ip address and ipv4mask criteria.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文