gpt4 book ai didi

c# - 通过子网掩码计算IP范围

转载 作者:太空狗 更新时间:2023-10-29 20:54:55 25 4
gpt4 key购买 nike

如果我有子网掩码,例如255.255.255.0 和一个 IP 地址 192.168.1.5,是否有一种简单的方法来确定该子网中所有可能的 IP 地址?

在这种情况下:

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
...
...
192.168.1.252
192.168.1.253
192.168.1.254
192.168.1.255

到目前为止,我发现的都是重载的 .net 库。有没有使用默认 namespace 解决此问题的本地方法?

最佳答案

10 分钟的编码,未经过全面测试:

class IPSegment {

private UInt32 _ip;
private UInt32 _mask;

public IPSegment(string ip, string mask) {
_ip = ip.ParseIp();
_mask = mask.ParseIp();
}

public UInt32 NumberOfHosts {
get { return ~_mask+1; }
}

public UInt32 NetworkAddress {
get { return _ip & _mask; }
}

public UInt32 BroadcastAddress {
get { return NetworkAddress + ~_mask; }
}

public IEnumerable<UInt32> Hosts(){
for (var host = NetworkAddress+1; host < BroadcastAddress; host++) {
yield return host;
}
}

}

public static class IpHelpers {
public static string ToIpString(this UInt32 value) {
var bitmask = 0xff000000;
var parts = new string[4];
for (var i = 0; i < 4; i++) {
var masked = (value & bitmask) >> ((3-i)*8);
bitmask >>= 8;
parts[i] = masked.ToString(CultureInfo.InvariantCulture);
}
return String.Join(".", parts);
}

public static UInt32 ParseIp(this string ipAddress) {
var splitted = ipAddress.Split('.');
UInt32 ip = 0;
for (var i = 0; i < 4; i++) {
ip = (ip << 8) + UInt32.Parse(splitted[i]);
}
return ip;
}
}

用法:

    static void Main(string[] args) {

IPSegment ip = new IPSegment("192.168.1.1","255.255.255.248");

Console.WriteLine(ip.NumberOfHosts);
Console.WriteLine(ip.NetworkAddress.ToIpString());
Console.WriteLine(ip.BroadcastAddress.ToIpString());

Console.WriteLine("===");
foreach (var host in ip.Hosts()) {
Console.WriteLine(host.ToIpString());
}
Console.ReadLine();

}

关于c# - 通过子网掩码计算IP范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com