How to install a custom SocketFactory to control local ports usage
jduprezJun 29 2009 — edited Mar 15 2011Hello,
I am plagued by a problem which I think is tracable to a client apllication trying to reuse local ports of formerly closed sockets before the ports are rendered available (for those interested, see the overall problem described in [another thread|http://forums.sun.com/thread.jspa?threadID=5394391] ).
I think one of the way to avoid this problem would be to inject custom code that intercept socket creation or opening, to either:
- set specific socket options (SO_LINGER for example)
- or enforce a given local port usage policy (such as, elect the port into a range of free ports).
I found out in the Javadoc that a SocketImplFactory can be installed at startup (static method Socket.setSocketImplFactory(...)). However I have two difficulties:
1) I am not able (and not willing) to reimplement a whole socket layer. Ideally I would just want to implement a wrapper factory, that wraps a default SocketImplFactory. But I haven't found such a default factory class. Reading the JDK's Socket code shows that in the absence of a factory, a SocksSocketImpl is instantiated.
2) So I guess I could implement a factory that instantiates a SocksSocketImpl and specifies the local port to be used. However it isn't clear how a local port can be enforced. There is no setLocalPort() exposed in class SocketImpl. Apparently I could subclass SocksSocketImpl and override getLocalPort() to return a local port that abide to my custom policy. However I find no example of this either in the JDK source nor on the Web.
I'll try this approach tomorrow.
But I'm inclined, as per my fruitless internet searches, to believe that local ports are very seldom enforced in Java applications - they merely seem let to the OS to dynamically elect whichever local port is deemed free. Has anyone experience with that?
Before ending, is there a more straightforward approach, such as an undocumented JVM option that would specify a local port selection policy?