Click here to Skip to main content
13,195,710 members (55,585 online)
Click here to Skip to main content
Add your own
alternative version


109 bookmarked
Posted 19 Jul 2003

Packet Filtering in .NET

, 19 Jul 2003
Rate this:
Please Sign up or sign in to vote.
Class library to implement packet filtering funcionality in your .NET applications


Recently, I have been searching on how I can make filter applications using Packet Filtering API included in Windows 2000 and above. First, I decided to make a C++ class in order to encapsulate all and make easy next applications. But I thought... why don't write a .NET C++ class? Because I haven't seen any other class to do it for this platform, I answered "yes".

The problem is that I am a beginner with .NET. I know C++ and I have used C# a few times, but I haven't written mix managed/unmanaged C++ code ever. Anyway, I didn't change my answer, I decided to write this class and I'll write it :P (and in this way, I can learn more about .NET). For this reason, you may see bugs in my code or probably you might think you would write code better. Feel free to tell me all you think and we will learn together. You will learn something about packet filtering ( I hope it...) and I learn something about .NET mixing managed/unmanaged code (I hope it, too).

Packet Filtering API

With Windows 2000, Microsoft included one API in order to implement packet filtering functionality in our programs. This API is included in Windows XP and Windows 2003, too. Packet Filtering API allow us to associate filters to IP adapter interfaces. We can implement a functionality similar that included in TCP/IP filter options in TCP/IP properties of a network adapter. Now I will comment the basic functions for this API, used to write this class:

  • PfCreateInterface(...)

    Used to create an interface. In this function, we pass the default action for incoming and outgoing packets. Then, we associate filters to interfaces.

  • PfBindInterfaceToIPAddress(...)

    We created a interface, but we have to bind it with a IP address. To do it, we use this function.

  • PfAddFiltersToInterface(...)

    We have created the interface and bind it with a local IP. Now, we can associate filters in order to filter IP traffic. When we created the interface, we indicated the default action for incoming and outgoing packets. The filters reverse the default actions for the interface.

  • PfAddGlobalFilterToInterface(...)

    Add a global filter to all filters of an interface. We have three predefined global filters: check packets fragments, check fragments from the cache, check destination for incoming packets (check IP spoofing attacks).

  • PfRemoveGlobalFilterToInterface(...)

    Remove a global filter from an interface.

  • PfRemoveFiltersFromInterface(...)

    Remove an added filter from an interface.

  • PfUnBindInterface(...)

    Unbind an IP address and an interface.

  • PfDeleteInterface(...)

    Delete an interface created.

If you want more information about this functions parameters, you can find it in MSDN. One reason to write this article is the few documentation (I love documentation with samples!!!). Important: You can only use this functions if you have administrative privileges.

Installing our IP Filters

We know the functions we have to use. Now we have to know the process to install filters:

  1. We must know the IP address of the local interface where we want to apply packet filtering. The initial process is easy: create the interface and bind the known local IP address with it.
  2. Second, we add the filter rules as we want. We can add filter rules or global filters.
  3. When we finish, we must unbind interfaces and local IP address and delete interfaces created.

In C words:

<PRE lang=c++>// Creating the interface and associating it with // a local ip address INTERFACE_HANDLE hInterface; PfCreateInterface(0, PF_ACTION_FORWARD, PF_ACTION_FORWARD, FALSE, TRUE, &hInterface); // look this byte order for ip address!! BYTE localIp[] = {172,29,16,2}; PfBindInterfaceToIPAddress(hInterface, PF_IPV4, localIp); // We go to add a filter. Forbid outgoing http traffic, for example. FILTER_HANDLE fHandle; // Fill the filter rule data PF_FILTER_DESCRIPTOR inFilter; inFilter.dwFilterFlags = FD_FLAGS_NOSYN; //always this value inFilter.dwRule = 0; //always this value inFilter.pfatType = PF_IPV4; //using ipV4 addresses inFilter.SrcAddr = localIp; //set local ip inFilter.SrcMask = "\xff\xff\xff\xff"; //mask for local ip inFilter.wSrcPort = FILTER_TCPUDP_PORT_ANY; //any source port inFilter.wSrcPortHighRange = FILTER_TCPUDP_PORT_ANY; inFilter.DstAddr = 0; //any destination inFilter.DstMask = 0; inFilter.wDstPort = 80; //destination port 80(http service) inFilter.wDstPortHighRange = 80; inFilter.dwProtocol = FILTER_PROTO_TCP; // Tcp protocol // Add the filter PfAddFiltersToInterface(hInterface, 1, &inFilter, 0, NULL, &fHandle); //............... //............... // Remove the filter PfRemoveFilterHandles(hInterface, 1, &fHandle); // Unbind and delete interface PfUnBindInterface(hInterface); PfDeleteInterface(hInterface);

The .NET Classes

My packet filtering API for .NET implements two public classes:

  • TxFilterController.

    The basic class. Used to add filters or remove filters to an interface. You can implement filtering only with this class. This class create only the interfaces needed, without requiring the user to do it.

    Its methods are as follows:

    • int AddFilter(IPAddress *ip, TxIpFilter *filter)

      Add a filter to a local IP address. If no error, return 0. This method is overloaded in order to pass the filter rules without creating a TxIpFilter object. Packets that matches a filter rule will be dropped.

    • int AddGlobalFilter(IPAddress *ip, int globalFilter)

      Add a global filter to a local IP address. If no error return 0.

    • int RevomeFilter(IPAddress *ip, TxIpFilter *filter)

      Remove a filter from an interface. If no error, return 0. This method is overloaded in order to pass the filter rules without creating a TxIpFilter object.

    • int RevomeGlobalFilter(IPAddress *ip, int globalFilter)

      Remove a global filter from an interface. If no error, return 0.

    • CloseController()

      Remove and unbind all interfaces created.

  • TxIpFilter.

    The equivalent of PF_FILTER_DESCRIPTOR in packet filtering API. Define a filter rule. You can add as TxIpFilters as you want to TxFilterController.

Sample application

To test the class, I wrote a simple C# application that installs two rules: forbid all incoming ICMP traffic and forbid all outgoing HTTP traffic. You can see how I use my classes, seeing the code:

static void Main(string[] args) 
    TxFilterController fltCont = new TxFilterController();
    TxIpFilter flt = new TxIpFilter(); 

    // Not icmp traffic 
    // For    icmp traffic: 
    // source port = icmp type 
    // destination port = icmp code 
    flt.direction       = TxIpFilter.IN_DIRECTION; 
    flt.ipSource        = IPAddress.Any; 
    flt.maskSource      = IPAddress.Any; 
    flt.ipDestination   = IPAddress.Any; 
    flt.maskDestination = IPAddress.Any; 
    flt.protocol        = TxIpFilter.ICMP_PROTOCOL; 
    flt.sourcePort      = TxIpFilter.ANY_ICMP_TYPES; 
    flt.destinationPort = TxIpFilter.ANY_ICMP_TYPES; 
    fltCont.AddFilter(IPAddress.Parse(""), flt);

    // Not allow outgoing http traffic



Where can you use this class? You can use in applications where you can add easily, packet filtering functionality. You can use in a complete filtering application because this API is few flexible: you can only filter at IP and transport level (IPs, ports and protocol), don't filter at link level and don't filter at application level.

I don't know if you can use Packet Filtering API with Wan interfaces, because I don't have a modem to test. If you test it, please tell me the result.

And... that's all. I hope this class will be useful for somebody.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Jesus Oliva
Chief Technology Officer
Spain Spain
To summarize: learn, learn, learn... and then try to remember something I.... I don't Know what i have to remember...

You may also be interested in...

Comments and Discussions

QuestionThings have changed from windows vista onwards Pin
Dr Gadgit27-Jul-15 11:41
memberDr Gadgit27-Jul-15 11:41 
QuestionI can't download the source code,why? Pin
cyl06162-Sep-12 16:43
membercyl06162-Sep-12 16:43 
GeneralMy vote of 5 Pin
wserra1-Mar-12 19:26
memberwserra1-Mar-12 19:26 
QuestionHow add multi-port in one rule? Pin
lamhung6-Oct-11 17:18
memberlamhung6-Oct-11 17:18 
AnswerRe: How add multi-port in one rule? Pin
cyl06162-Sep-12 16:55
membercyl06162-Sep-12 16:55 
Questionworks on windows? Pin
xsymail9-Jan-11 22:12
memberxsymail9-Jan-11 22:12 
AnswerRe: works on windows? Pin
AlexandreDrouin19-Apr-11 18:02
memberAlexandreDrouin19-Apr-11 18:02 
GeneralFilter works but i still get "connected" / "disconnected" on the server on destination IP Pin
qinta18-Nov-09 3:37
memberqinta18-Nov-09 3:37 
GeneralConfused about code, no documentation Pin
Jordanwb7-Nov-09 12:27
memberJordanwb7-Nov-09 12:27 
GeneralRe: Confused about code, no documentation Pin
Jordanwb7-Nov-09 12:46
memberJordanwb7-Nov-09 12:46 
GeneralVery nice article and it helped me alot Pin
Srikanth. Vemulapalli7-May-09 4:36
memberSrikanth. Vemulapalli7-May-09 4:36 
Generalplease correct this in your source code. the example do not work correctly because of this Pin
Christian Salazar15-Feb-09 6:49
memberChristian Salazar15-Feb-09 6:49 
GeneralRe: please correct this in your source code. the example do not work correctly because of this Pin
Jordanwb7-Nov-09 12:22
memberJordanwb7-Nov-09 12:22 
GeneralRe: please correct this in your source code. the example do not work correctly because of this Pin
Christian Salazar7-Nov-09 14:49
memberChristian Salazar7-Nov-09 14:49 
GeneralDefault firewall rule:Disable everything Pin
gunnarJonsson28-Oct-08 2:05
membergunnarJonsson28-Oct-08 2:05 
QuestionObtain packets Pin
Radu_2029-Sep-08 4:27
memberRadu_2029-Sep-08 4:27 
QuestionRestricting web access through code Pin
Chuks Ogbechie12-Jul-07 5:40
memberChuks Ogbechie12-Jul-07 5:40 
QuestionIs it possible to block a specific IP? Pin
NinethSense21-Jun-07 3:48
memberNinethSense21-Jun-07 3:48 
AnswerRe: Is it possible to block a specific IP? Pin
pku200930-Dec-08 20:16
memberpku200930-Dec-08 20:16 
GeneralHints Pin
balazs_hideghety19-Jun-07 19:56
memberbalazs_hideghety19-Jun-07 19:56 
GeneralOddly not working (Windows XP SP2) Pin
Matt.J15-Apr-07 23:01
memberMatt.J15-Apr-07 23:01 
GeneralRe: Oddly not working (Windows XP SP2) Pin
eic0906621-Apr-07 5:17
membereic0906621-Apr-07 5:17 
GeneralRe: Oddly not working (Windows XP SP2) Pin
eic0906624-Apr-07 8:22
membereic0906624-Apr-07 8:22 
GeneralCrash on Server 2003 Pin
jcarle20-Jan-07 18:50
memberjcarle20-Jan-07 18:50 
GeneralFilter on Adapters not IPs Pin
bbembi_de29-Oct-06 2:40
memberbbembi_de29-Oct-06 2:40 
AnswerRe: Filter on Adapters not IPs Pin
vonuyx26-Jan-07 6:33
membervonuyx26-Jan-07 6:33 
Questionudp wont work ? Pin
maxSEPHIROTH17-Oct-06 6:36
membermaxSEPHIROTH17-Oct-06 6:36 
QuestionNeed help in modifying the application Pin
Sudeep Kukreti8-Aug-06 2:18
memberSudeep Kukreti8-Aug-06 2:18 
AnswerRe: Need help in modifying the application Pin
devSOME16-Oct-06 22:31
memberdevSOME16-Oct-06 22:31 
GeneralRe: Need help in modifying the application Pin
Sudeep Kukreti16-Oct-06 22:51
memberSudeep Kukreti16-Oct-06 22:51 
QuestionHow do I use your code in another machines?? Pin
Cleyton Messias1-Aug-06 11:29
memberCleyton Messias1-Aug-06 11:29 
Generalnot well describled Pin
tasleem14331-Jul-06 3:41
membertasleem14331-Jul-06 3:41 
GeneralRe: not well describled Pin
pku200930-Dec-08 20:30
memberpku200930-Dec-08 20:30 
Generalit did not work [modified] Pin
tasleem14329-Jul-06 4:13
membertasleem14329-Jul-06 4:13 
GeneralUnable to Block SYN packets Pin
SZKHAN10-Feb-06 5:55
memberSZKHAN10-Feb-06 5:55 
war_akon17-Jan-06 19:55
memberwar_akon17-Jan-06 19:55 
QuestionFiltering and saving Pin
Redaemon11-Jan-06 7:39
memberRedaemon11-Jan-06 7:39 
GeneralPacket Redirect Pin
Anonymous8-Oct-05 1:58
sussAnonymous8-Oct-05 1:58 
QuestionNewbie, problem with C++.NET Pin
tvbusy7-Oct-05 18:18
membertvbusy7-Oct-05 18:18 
Generalfunction of the program Pin
Anonymous--xlsl31-Jul-05 23:08
sussAnonymous--xlsl31-Jul-05 23:08 
QuestionFilter out SYN packet? Pin
Sam Lin4-Jul-05 21:21
memberSam Lin4-Jul-05 21:21 
GeneralGood Thing Pin
Anonymous21-Apr-05 20:44
sussAnonymous21-Apr-05 20:44 
GeneralRe: Good Thing Pin
Anonymous21-Apr-05 21:16
sussAnonymous21-Apr-05 21:16 
GeneralRe: Good Thing Pin
Anonymous21-Apr-05 21:33
sussAnonymous21-Apr-05 21:33 
Generalhelp with packet filtering iamicaly Pin
viejoned21-Apr-05 10:26
memberviejoned21-Apr-05 10:26 
AnswerRe: help with packet filtering iamicaly Pin
Behind The Scene31-Dec-06 3:42
memberBehind The Scene31-Dec-06 3:42 
GeneralRules to allow Pin
pkapfer4-Apr-05 7:58
memberpkapfer4-Apr-05 7:58 
QuestionWhat about other protocol Pin
tamnet198320-Feb-05 13:52
membertamnet198320-Feb-05 13:52 
GeneralAccessing the api from c# Pin
sciamachy13-Dec-04 4:45
membersciamachy13-Dec-04 4:45 
GeneralRe: Accessing the api from c# Pin
Jesús O.13-Dec-04 5:28
memberJesús O.13-Dec-04 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171019.1 | Last Updated 20 Jul 2003
Article Copyright 2003 by Jesus Oliva
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid