RC1140
RC1140

Reputation: 8663

Blocking Connections By IP

I need to able to block any and all connections to my pc from a specific IP address , i know this is possible with a firewall but i need to do this in c#. Any idea how (need code).

Update : Its a generic C# app not asp.net , target platform is WinXp till Win7

Upvotes: 1

Views: 2945

Answers (3)

Brandon
Brandon

Reputation: 14196

Need more information... if you're talking socket communication, you can simply close the connection to a client as soon as it connects if the IP address is blocked, or process the Connection Request and evaluate there.

Edit: Simplest way for you would probably just be to interact with Windows Firewall API... here's how:

http://www.shafqatahmed.com/2008/01/controlling-win.html

Upvotes: 4

Emiswelt
Emiswelt

Reputation: 4009

A "firewall" in c#?

First you would have to access the network interface on a low level, eg.: http://msdn.microsoft.com/en-us/library/ms817945.aspx

Then you have to parse all incoming packets and maybe discard them.

It's not an easy task and I don't recommend you to write a driver and a firewall in C#, because the .NET Framework will be loaded every time you start your machine. Also traffic parsing can be tricky... I implemented a router/traffic analyzer in C# some time ago and it took me about one year to gain the experience with network programming to gain the knowledge to do this.

Upvotes: 0

user29117
user29117

Reputation: 87

Your question is unclear but I'll try to answer the best I can, within my understanding.

  1. Do you want to control machines from connecting to any port on your machine? if so, you need to control the built-in windows firewall or find yourself a filter driver you can control. In order to write your own filter driver, you must leave the land of managed code, so I am guessing that's not an option.

To learn how to control the firewall, here's a link:

http://www.shafqatahmed.com/2008/01/controlling-win.html

more on google.

  1. Do you want to control remote machines from connection to a port on your machines that your application owns? You cannot do that either (see #1 above). However you can take action after the connection, and close the connection if you don't like the remote IP (check the remote endpoint's IP).

two caveats with this approach:

It doesn't save you from a DoS attack. You will need to be careful if you need ipv6 support (you can't just check the IPV4 address in that case)

HTH

Upvotes: 0

Related Questions