IPNetworkPrefix Class
The IPNetworkPrefix
struct represents an IPv4 or IPv6 network prefix, providing methods for containment checks, range calculations, and string formatting.
Namespace
System.Net.IP
Assembly
System.Net.Primitives.dll
Declaration
public readonly struct IPNetworkPrefix : IEquatable<IPNetworkPrefix>, IComparable<IPNetworkPrefix>
Properties
Name | Type | Description |
---|---|---|
Address | IPAddress | The base address of the network prefix. |
PrefixLength | int | The number of leading bits that define the network portion. |
NetworkMask | IPAddress | The subnet mask derived from PrefixLength . |
Broadcast | IPAddress | The broadcast address for the prefix (IPv4 only). |
Methods
Signature | Returns | Description |
---|---|---|
bool Contains(IPAddress address) | bool | Determines whether the specified address falls within the prefix. |
bool Overlaps(IPNetworkPrefix other) | bool | Checks if this prefix overlaps with another prefix. |
int CompareTo(IPNetworkPrefix other) | int | Compares two prefixes for sorting. |
bool Equals(IPNetworkPrefix other) | bool | Equality comparison. |
string ToString() | string | Returns the CIDR notation (e.g., 192.168.0.0/24 ). |
static IPNetworkPrefix Parse(string cidr) | IPNetworkPrefix | Parses a CIDR-formatted string. |
Example
using System;
using System.Net;
class Program
{
static void Main()
{
// Define a network prefix using CIDR notation
IPNetworkPrefix prefix = IPNetworkPrefix.Parse("192.168.1.0/24");
// Check if an IP address belongs to the prefix
IPAddress addr1 = IPAddress.Parse("192.168.1.45");
IPAddress addr2 = IPAddress.Parse("192.168.2.10");
Console.WriteLine($"{addr1} in {prefix}: {prefix.Contains(addr1)}");
Console.WriteLine($"{addr2} in {prefix}: {prefix.Contains(addr2)}");
// Output the broadcast address (IPv4 only)
Console.WriteLine($"Broadcast address: {prefix.Broadcast}");
}
}