This kind of thing is normally done using a separate firewall (e.g. in a router or gateway box) or firewall software running on one or both of the client machines.
This is not the sort of thing that it is sensible to implement in Java.
EDIT - in response to this followup
I am aware that such a thing is not advisable in Java..but still ill have to implement it..so is there any means to do so..?
Let us assume that you are talking about implementing a client-side firewall on a Linux machine. I can think of two approaches:
You could use Process.execute()
and friends to run the Linux iptables(8)
admin utility which manipulates the OS kernel's network packet filters. This is the simplest Java-based approach. But it requires that your Java app runs as root
.
You could reverse engineer what iptables(8)
is doing to manipulate the packet filters and code the same functionality in Java. That would be more coding work, including implementing parts of the functionality in C via JNI or JNA. And your app needs to run as root
.
But a far, far simpler approach is to simply run iptables(8)
from the command line, or make your changes using the fancy GUI-based admin tools.
Note that in the scenarios above, the firewall itself is not implemented in Java. All you are doing is administering the firewall from a Java application. I cannot think of ANY way to actually do the filtering / blocking in Java that is even remotely practical.