java - Check port usage at runtime? -
in application, during runtime, able identify if particular port being used (pretty easy this)
public static boolean portavailable(int port) { try (socket ignored = new socket("localhost", port)) { return false; } catch (ioexception ignored) { return true; } }
but information possible using port. stuff process id, name etc. how go doing this?
java not provide information looking for. have use os-specific apis instead.
i don't know *nix systems, on windows can owning process id tcp socket using gettcptable2()
/gettcp6table2()
or getextendedtcptable()
enumerate tcp sockets until find ip/port interested in. udp, there getextendedudptable()
function (and there getudptable()
, getudp6table()
functions, not provide owner process ids).
once have process id, can filename either:
using
createtoolhelp32snapshot()
/process32first()
/process32next()
enumerate running processes until find matching process id.using
openprocess()
directly open process of given process id, , query process's filename usinggetmodulefilenameex()
,getprocessimagefilename()
, orqueryfullprocessimagename()
.
Comments
Post a Comment