MSDN Documentation

Search

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

NameTypeDescription
AddressIPAddressThe base address of the network prefix.
PrefixLengthintThe number of leading bits that define the network portion.
NetworkMaskIPAddressThe subnet mask derived from PrefixLength.
BroadcastIPAddressThe broadcast address for the prefix (IPv4 only).

Methods

SignatureReturnsDescription
bool Contains(IPAddress address)boolDetermines whether the specified address falls within the prefix.
bool Overlaps(IPNetworkPrefix other)boolChecks if this prefix overlaps with another prefix.
int CompareTo(IPNetworkPrefix other)intCompares two prefixes for sorting.
bool Equals(IPNetworkPrefix other)boolEquality comparison.
string ToString()stringReturns the CIDR notation (e.g., 192.168.0.0/24).
static IPNetworkPrefix Parse(string cidr)IPNetworkPrefixParses 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}");
    }
}

See Also