This is Linux dependent code, but not difficult to port to Windows.
This is not a Servlet code, but would work in that case as well:
Lets say I've a ServerSocket waiting on accept() call. When it receives a client request, it creates a Socket at another port to deal with that 'remote' request.
ServerSocket ss = new ServerSocket(2000);
System.out.println("Listening on local port : " + ss.getLocalPort());
while(...)
{
Socket s = ss.accept();
System.out.println("accepted client request, opened local port : " + s.getPort());
...
}
So, you need to feed the output of s.getPort() from above snippet to the following program's main() method.
public class FindUserByPort
{
public static void main(String[] args) throws Exception
{
String cmd = "netstat -anp | grep ";
int port = Integer.valueOf(args[0]);
cmd = cmd + port ;
Process pr = Runtime.getRuntime().exec(cmd);
InputStream is = pr.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
List<Integer> pIDs = new ArrayList<Integer>();
while ((line = br.readLine()) != null)
{
if (line.contains("127.0.0.1:" + port))
{
String pidPname = line.substring(line.indexOf("ESTABLISHED") + "ESTABLISHED".length());
pidPname = pidPname.trim();
String pid = pidPname.split("/")[0];
pIDs.add(Integer.valueOf(pid));
}
}
if (pIDs.size() > 0)
{
for (int pid : pIDs)
{
String command = "top -n1 -b -p " + pid ;
Process p = Runtime.getRuntime().exec(command);
InputStream _is = p.getInputStream();
BufferedReader _br = new BufferedReader(new InputStreamReader(_is));
String _line = null;
while ((_line = _br.readLine()) != null)
{
_line = _line.trim();
if(_line.startsWith(String.valueOf(pid)))
{
String[] values = _line.split(" ");
System.out.println("pid : " + pid + ", user : " + values[1]);
}
}
_is.close();
_br.close();
}
}
is.close();
br.close();
}
}