Showing revision 1

AWK script as simple netstat replacement

Sometimes the netstat tool is not available, even intentional as in containers which should be minimal. A simple AWK script can nicely format the information from the Linux /proc filesystem.

The script supports IPv6 connections, is tested with mawk and gawk and based on https://gist.github.com/qistoph/1b0708c888f078c3720de6c6f9562997.

[upload:awk_netstat.sh Download]

Code

#!/bin/sh

# AWK script to format Linux /proc/net/tcp[6] as simple netstat tool
# based on https://gist.github.com/qistoph/1b0708c888f078c3720de6c6f9562997

mawk -W posix -- '
BEGIN{
    states["01"]="ESTABLISHED"
    states["02"]="SYN_SENT"
    states["03"]="SYN_RECV"
    states["04"]="FIN_WAIT1"
    states["05"]="FIN_WAIT2"
    states["06"]="TIME_WAIT"
    states["07"]="CLOSE"
    states["08"]="CLOSE_WAIT"
    states["09"]="LAST_ACK"
    states["0A"]="LISTEN"
    states["0B"]="CLOSING"
}
function hextodec(str) {
    return sprintf("%d", "0x" str)
}
function compactip6(str,ret,i,len) {
    ret=str
    for (i=1; i<=length(str) && match(substr(str,i), /(^|:)0(:0)*(:|$)/); i+=RLENGTH) {
        if (RLENGTH>=len) {
            ret=substr(str,1,i+RSTART-2) "::" substr(str,i+RSTART+RLENGTH-1)
            len=RLENGTH
        }
    }
    return ret
}
function getip(str,ret,i,s) {
    if (length(str)==13){
        for (i=7; i>0; i-=2) {
            ret=ret substr(".",1,i<7) hextodec(substr(str,i,2))
        }
    } else {
        for (i=5; i<32; i+=i%8==1?12:-4) {
            s=tolower(substr(str,i+2,2) substr(str,i,2))
            sub(/^0(00?)?/,"",s)
            ret=ret substr(":",1,i!=5) s
        }
        ret=compactip6(ret)
    }
    ret=ret ":" hextodec(substr(str,index(str,":")+1,4))
    return ret
}
/^ *[0-9]/ { if(NR==2) print "Local - Remote State"; print getip($2)" - "getip($3)" "states[$4] }' /proc/net/tcp /proc/net/tcp6