Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created June 11, 2013 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/5754906 to your computer and use it in GitHub Desktop.
Save elazarl/5754906 to your computer and use it in GitHub Desktop.
This test shows that Java will not allow a socket to connect to itself via TCP's simultaneous connection feature, by setting the source port identical to the destination port.
import org.junit.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
/**
* This tests make sure Java prevents a socket from connecting to itself
* via binding to the same port it connects to
*/
public class LoopBackSocket {
@Test(expected = SocketException.class)
public void testNoLoopbackSymConnection() throws Exception {
final InetAddress localhost = InetAddress.getLocalHost();
Socket socket = new Socket();
socket.bind(new InetSocketAddress(localhost, 7777));
socket.connect(new InetSocketAddress(localhost, 7777));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment