09.11.2017, 11:49
You can filter the result by local port (80 or 443) and also by TCP state. TCP_ESTABLISHED should be enough since visualization uses web sockets where connection is always open during an active session.
Code:
states = {
'TCP_ESTABLISHED',
'TCP_SYN_SENT',
'TCP_SYN_RECV',
'TCP_FIN_WAIT1',
'TCP_FIN_WAIT2',
'TCP_TIME_WAIT',
'TCP_CLOSE',
'TCP_CLOSE_WAIT',
'TCP_LAST_ACK',
'TCP_LISTEN',
'TCP_CLOSING',
};
-- convert hex to readable IP
function toip(hex)
local res = {}
for i = 4, 1, -1 do
local j = (i - 1) * 2 + 1
local ch = hex:sub(j, j + 1)
res[ #res + 1 ] = tonumber(ch, 16)
end
return table.concat(res, '.')
end
for line in io.lines('/proc/net/tcp') do
local_ip, local_port, remote_ip, remote_port, state =
line:match('(%x+):(%x+)%s+(%x+):(%x+)%s+(%x+)')
-- valid line
if local_ip and local_port and remote_ip and remote_port and state then
local_ip = toip(local_ip)
local_port = tonumber(local_port, 16)
remote_ip = toip(remote_ip)
remote_port = tonumber(remote_port, 16)
state = states[ tonumber(state, 16) ]
log(local_ip, local_port, remote_ip, remote_port, state)
end
end