Reputation: 6774
How could I temporarily disable a network connection in Java?
Upvotes: 9
Views: 7669
Reputation: 4584
Sniffy allows you to block outgoing network connections in your Java applications - it will throw a ConnectException
whenever you try to establish a new connection to restricted host.
Just add -javaagent:sniffy.jar=5559
to your JVM arguments and point your browser to localhost:5559
- it will open a web page with all discovered connections to downstream systems and controls to disable certain connections.
If your application is web-based, you can even do it directly from your application opened in browser - see a demo here: http://demo.sniffy.io/owners?lastName=
Click on a widget in bottom-right corner, select Network Connections
tab, disable and connection to localhost:8967
(database) and reload a page to see it in action.
Disclaimer: I'm the author of Sniffy
Upvotes: 2
Reputation: 1
you can disable all interfaces using wmic path win32_networkadapter
where PhysicalAdapter = True
call disable
Upvotes: 0
Reputation: 48659
(Assuming this is under Windows, Vista or later)
You can disable an interface via WMI, which can be accessed through a bridge such as JACOB.
Upvotes: 1
Reputation: 49804
A fairly complicated but feasible way to do this is to create a custom socket implementation factory. You can register it by calling Socket.setSocketImplFactory()
.
Your custom factory will then have to return custom socket implementations that simply throw an IOException
at every connection attempt.
Note that this only stops outgoing connections, if you want to stop your application accepting incoming connections as well, you'll have to play a similar trick on ServerSocket
s.
Upvotes: 4
Reputation: 3859
Would these work? On windows:
Runtime.getRuntime ().exec ("ipconfig/release");
On linux ( assuming the network interface is called eth0:
Runtime.getRuntime ().exec ("ifconfig eth0 down");
Upvotes: 2
Reputation: 87603
Unfortunately, disabling a network connection is OS-specific and I'm not aware of any standard Java APIs for accessing those OS features. You'd probably have to do some OS-specific coding, e.g. via JNI or executing external programs, for each OS you intend to support. The Java program would also need to be invoked with the proper privileges to be allowed to mess with the network interfaces.
Upvotes: 2