im running the following bit of code, which just connects and closes a socket in an infinite loop:
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
public class Main {
public static void main(String[] args) throws Exception {
Thread.sleep(1000);
InetAddress localhost = InetAddress.getByName("127.0.0.1");
InetSocketAddress localhostRpcbind = new InetSocketAddress(localhost, 111);
SelectorProvider selectorProvider = SelectorProvider.provider();
long iterations = 0;
while (true) {
try {
SocketChannel socketChannel = selectorProvider.openSocketChannel();
socketChannel.connect(localhostRpcbind);
socketChannel.finishConnect();
socketChannel.close();
iterations ++;
} catch (Exception e) {
System.err.println("after " + iterations + " iterations");
e.printStackTrace(System.err);
throw e;
}
}
}
}
port 111 is the port for rpcbind (which is up and running on my machine). on the 1st run of the code i'll get something like:
after 28239 iterations
java.net.BindException: Cannot assign requested address
at sun.nio.ch.Net.connect0(Native Method)
at sun.nio.ch.Net.connect(Net.java:458)
at sun.nio.ch.Net.connect(Net.java:450)
at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:648)
at Main.main(Main.java:16)
subsequent runs will fail immediately (0 iterations), until after a while i get the 1st result again (~26-28k iterations then a failure).
whats going on and how can i get this connect/disconnect loop to properly run indefinitely?
im running on linux x64 (fedora 22).
note: yes, i know the code is useless and does nothing, this is a SSCCE of a bigger issue i'm trying to investigate.
UPDATE - looks like im running into ephemeral port exhaustion on my machine:
$ cat /proc/sys/net/ipv4/ip_local_port_range
32768 61000
so i have ~28k ephemeral ports to use for connections, which matches up with my error