MSDN > Documentation > .NET > APIs > Networking > System.Net.IP > IPAddressPolicyFilter

IPAddressPolicyFilter Class

Represents a filter for IP address policies.

Namespace

System.Net.IP

Assembly

System.Net.Primitives.dll

Syntax


public class IPAddressPolicyFilter
        

Remarks

The IPAddressPolicyFilter class provides a mechanism to define and apply policies for IP addresses. This can be used to control access, validate addresses, or enforce specific network configurations. It allows for flexible definition of rules based on IP address properties such as range, type, and associated network segments.

Methods

Matches

public bool Matches(IPAddress address)

Determines whether the specified IP address matches the criteria defined by this policy filter.

Parameters
Name Type Description
address IPAddress The IP address to check against the policy.
Returns

true if the IP address matches the policy; otherwise, false.

Properties

Allowed

public IPAddressCollection Allowed { get; set; }

Gets or sets a collection of IP addresses that are explicitly allowed by this policy filter.

Denied

public IPAddressCollection Denied { get; set; }

Gets or sets a collection of IP addresses that are explicitly denied by this policy filter.

DefaultAction

public PolicyAction DefaultAction { get; set; }

Gets or sets the default action to take for IP addresses that do not match any specific rules.

The possible values for PolicyAction are Allow and Deny.

Example

The following example demonstrates how to create an IPAddressPolicyFilter to allow access from a specific IP address and deny all others.


using System;
using System.Net;
using System.Net.IP; // Assuming this namespace contains IPAddressCollection and PolicyAction

// Create a collection for allowed IP addresses
var allowedAddresses = new IPAddressCollection();
allowedAddresses.Add(IPAddress.Parse("192.168.1.100"));

// Create a policy filter
var policyFilter = new IPAddressPolicyFilter
{
    Allowed = allowedAddresses,
    DefaultAction = PolicyAction.Deny // Deny all by default
};

// IP address to test
IPAddress testAddress1 = IPAddress.Parse("192.168.1.100");
IPAddress testAddress2 = IPAddress.Parse("10.0.0.5");

// Check if the addresses match the policy
bool isAllowed1 = policyFilter.Matches(testAddress1); // Should be true
bool isAllowed2 = policyFilter.Matches(testAddress2); // Should be false

Console.WriteLine($"Address {testAddress1} is allowed: {isAllowed1}");
Console.WriteLine($"Address {testAddress2} is allowed: {isAllowed2}");