How To: Server Socket Hijacking in Java
Overview
Socket hijacking allows you to override a server socket opened on the same port by a different process. There are several good uses of socket hijacking like developing a port blocker application (poor man's firewall) and some bad uses too.
Normally the operating system doesn't allow you to open a server socket on a port which is already opened by another (or even the same) application. However there is an exception and an exception to the exception.
What and how of socket hijacking
Often a ServerSocket is opened without specifying a particular IP address to bind to. So the socket essentially binds to all available IP address of the machine. This is simple for the programmer. However it introduces a security hole. Any application can bind to a specific IP address of the same machine and on the same port. The original server socket still binds on the remaining port. In essence the port has been hijacked by the new application for a specific IP address. This is socket hijacking.
Java support for socket hijacking
Starting with JDK 1.4 Java supports the method ServerSocket.setReuseAddress(boolean). It allows you to hijack a port for a particular IP address as described above. Here is a sample code which allows you to hijack a server socket.
Code
ServerSocket ssock = new ServerSocket();
ssock.setReuseAddress(true); // The magic
ssock.bind(new InetSocketAddress(addr, i)); // addr = IP, i = port
Socket sock = ssock.accept();
// Do your thing with the accepted connection
sock.close();
Filed under Headline News, How To, Java Software, Tech Note |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |




































November 16th, 2007 at 4:22 pm
I tried this hijacking, but did not get it work.
Only IP address I could bind to was localhost.
All other IP’s throw java.net.BindException: Cannot assign requested address: JVM_Bind?
November 18th, 2007 at 6:54 am
Does your computer (on which you are running this program) have this IP address?
Can you ping it?