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 Socket
object opened by the other thread, it just knows the number of the local port it would be listening on.
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: https://github.com/mss/java-netstat/blob/master/src/main/java/de/msquadrat/netstat/ConnectionState.java would be nice.
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 /proc/net
file system). I need something that is cross platform.
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 netstat
while no client is connected:
$ netstat -nap | fgrep 10010
tcp 0 0 0.0.0.0:10010 0.0.0.0:* LISTEN 20096/java
And the same output when a client is connected:
$ netstat -nap | fgrep 10010
tcp 0 0 192.168.101.94:10010 10.0.42.252:50426 ESTABLISHED 20096/java
And just for completeness, here's an example of a more traditional TCP server when just listening:
$ netstat -nap | fgrep 8080
tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN 20096/java
And that same server with one connected client:
$ 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
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 not the situation I have.