title: Is there any way to get the state of a socket connection in java given the port number
body: <p>Another thread in my server process listens on a specific port that my main thread knows the number of. The main thread doesn't have access to the actual <code>Socket</code> object opened by the other thread, it just knows the number of the local port it would be listening on.</p>
  
  <p>Is there a way to find out the state of this socket? I really only care about if it's listening vs. connected/established. But having access to all the states listed here: <a href="https://github.com/mss/java-netstat/blob/master/src/main/java/de/msquadrat/netstat/ConnectionState.java" rel="nofollow noreferrer">https://github.com/mss/java-netstat/blob/master/src/main/java/de/msquadrat/netstat/ConnectionState.java</a> would be nice.</p>
  
  <p>Now you might ask why I don't just use that project as it seems to do exactly what I'd want. Well, it only works on linux (or systems exposing the same <code>/proc/net</code> file system). I need something that is cross platform.</p>
  
  <p>Edit: To respond to some of the comments below. I don't have access to any objects from the thread that is either listening or connected. I don't have access to that code, so I can't keep a global table of the connection state myself. And yes, the connection will either be in state LISTEN or ESTABLISHED. There can only be one connected client at a time and while that client is connected, the server code will not still be listening on that port. Here's the output of <code>netstat</code> while no client is connected:</p>
  
  <pre><code>$ netstat -nap | fgrep 10010
  tcp        0      0 0.0.0.0:10010               0.0.0.0:*                   LISTEN      20096/java
  </code></pre>
  
  <p>And the same output when a client is connected:</p>
  
  <pre><code>$ netstat -nap | fgrep 10010
  tcp        0      0 192.168.101.94:10010        10.0.42.252:50426           ESTABLISHED 20096/java
  </code></pre>
  
  <p>And just for completeness, here's an example of a more traditional TCP server when just listening:</p>
  
  <pre><code>$ netstat -nap | fgrep 8080
  tcp        0      0 127.0.0.1:8080              0.0.0.0:*                   LISTEN      20096/java
  </code></pre>
  
  <p>And that same server with one connected client:</p>
  
  <pre><code>$ netstat -nap | fgrep 8080
  tcp        0      0 127.0.0.1:8080              0.0.0.0:*                   LISTEN      20096/java          
  tcp        0      0 127.0.0.1:8080              10.0.42.252:60660             ESTABLISHED 20096/java
  </code></pre>
  
  <p>As you can see, this server does what most servers do, it keeps listening after accepting a connection. So in that case there would be two sockets on that single local port, one in LISTEN and one in ESTABLISHED. But this is explicitly <strong>not</strong> the situation I have.</p>