0

As the title says how would one check the number of open connections to a webserver on port 80 and 443?

I'm currently using this oneliner to get the number of open connections per ipaddress from port 80:

netstat -tn 2>/dev/null | 
    grep :80 | 
    grep -i established |
    awk '{print $5}' | 
    cut -d: -f1 | 
    sort | 
    uniq -c | 
    sort -nr | 
    head

How would one add port number 443 to this query? I've tried the following:

netstat -tn 2>/dev/null | 
    grep ':80/|:443' | 
    grep -i established |
    awk '{print $5}' | 
    cut -d: -f1 | 
    sort | 
    uniq -c | 
    sort -nr | 
    head

but ended up getting 0 results did i do something wrong?

2 Answers 2

3

Try

netstat -ant | egrep '(:80|:443) .*:.*ESTABLISHED' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c

or

netstat -nt | awk '$4 ~ /:(143|993)$/ && $6 ~ /ESTABLISHED/ {print $5}' | cut -d: -f1 | sort | uniq -c
  • netstat -nt lists TCP connections without DNS lookups of the IP address
  • egrep ':(80|443) .*:.*ESTABLISHED' selects ESTABLISHED connections on ports 80 restricting to the local address
  • 'awk {print $5}' separates the remote address and port
  • cut -d: -f1 remotes the port
  • sort | uniq -c counts uniq ips

  • awk '$4 ~ /:(80|443)$/ && $6 ~ /ESTABLISHED/ {print $5}' selects remote ip for ESTABLISHED connections to local ports 80 and 443

Edit:

If you want to count connections by IP, you can use {print $4, $5} in the print statement.

You can match on different or multiple states by altering the match for $6, such as /(ESTAB|SYN)/ which will include opening connections.

5
  • I'd like to keep the IP so i can view how many connections there are per IP address.
    – Baklap4
    Jun 7, 2016 at 12:39
  • 1
    @Baklap4 Updated adding more awk based filter,
    – BillThor
    Jun 7, 2016 at 12:47
  • 1
    If you want the IP addresses you need -W as well. Without -W some of the IP addresses may be truncated by netstat. Also I noticed that if a client connects and don't send any data right away the TCP connection can show up as SYN_RECV rather than ESTABLISHED.
    – kasperd
    Dec 11, 2018 at 16:07
  • @kasperd Connections in SYN_RECV are in a half open state. This state indicates that the remote end hasn't completed opening the connection. Connections should not stay in this state very long, even if the other end does not send a request.
    – BillThor
    Dec 21, 2018 at 5:20
  • @BillThor That's what I thought too. But it turns out that's not always the case. An application can configure a socket in a way that will cause it to stay in SYN_RECV until the first data has been sent by the client. I was able to trigger that behavior with Apache running on Ubuntu LTS 14.04. Just telnet to port 80 on such a server and look at netstat output on the server.
    – kasperd
    Dec 21, 2018 at 10:51
0
- grep ':80/|:443'
+ egrep ':80|:443'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .