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();