【问题标题】:c# get the ip adress of the subnet networkc#获取子网网络的ip地址
【发布时间】:2017-06-26 09:45:17
【问题描述】:

如何获取网络的子网范围?例如,我的 ip 是 192.168.1.23 在网络子网范围内网络是 192.168.1.0 - 255 有没有使用 c# 或任何其他可以提供帮助的库为您提供此功能的方法?
- 我试图对一些常见的本地 IP 地址进行一些切换,但它仍然不能在生产中使用,因为有无数的情况取决于它的结构。
- 我试图搜索一些有用的解决方案,但我找不到任何有用的主题

提前致谢。

【问题讨论】:

标签: c#


【解决方案1】:
public static class IPAddressExtensions
{
    public static IPAddress GetBroadcastAddress(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] ^ 255));
        }
        return new IPAddress(broadcastAddress);
    }

    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(this IPAddress address2, IPAddress address, IPAddress subnetMask)
    {
        IPAddress network1 = address.GetNetworkAddress(subnetMask);
        IPAddress network2 = address2.GetNetworkAddress(subnetMask);

        return network1.Equals(network2);
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-04-15
  • 2018-11-24
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
相关资源
最近更新 更多