Skip to content

Instantly share code, notes, and snippets.

@helamonster
Created February 1, 2020 10:05
Show Gist options
  • Save helamonster/0af919b5ab969df1f5a4684d4cf4f4a7 to your computer and use it in GitHub Desktop.
Save helamonster/0af919b5ab969df1f5a4684d4cf4f4a7 to your computer and use it in GitHub Desktop.
How NOT to get the remote IP and port of a socket connection of a given process ID and listening port
# Here's another ridiculous thing, just for fun...
# Dont try this at home, kids.
# Your homework is to implement this in Go.
# See https://github.com/weaveworks/procspy for a head start.
# How to get the remote IP and port of socket connecting to the local machine
# (not necesarily localhost) on port 443 ( hex 0x01BB ) on given PID 13866
# Given a Process ID (PID), get list of sockets open:
$ ls -l /proc/13866/fd/ | grep socket | grep -o '\[.*\]' | sed 's/\[//;s/\]//'
666693188
666374737
666374739
666374740
# Match socket with system sockets to get line including source ip:port (3rd colum)
$ for STR in $(awk '{ if ($10 == 666374737 && $2~/:01BB$/ ) \
{ gsub(/:/, " ", $3) ; print $3 } }' < /proc/net/tcp) ; do echo $STR ; done
1B49B60A
D1AF
# Reformat output for printf parsing
$ for STR in $(awk '{ if ($10 == 666374737 && $2~/:01BB$/ ) \
{ gsub(/:/, " ", $3) ; print $3 } }' < /proc/net/tcp) ; do echo $STR ; done \
| sed 's/^\(..\)\(..\)\(..\)\(..\)$/0x\4 0x\3 0x\2 0x\1\n/g;s/^\(..\)\(..\)$/0x\2\1/g'
0x0A 0xB6 0x49 0x1B
0xAFD1
# Looping sockets and more reformatting
$ for SOCKET in $(ls -l /proc/13866/fd/ | grep socket | grep -o '\[.*\]' \
| sed 's/\[//;s/\]//' ) ; do echo $(for STR in $(awk '{ if ($10 == '$SOCKET' \
&& $2~/:01BB$/ ) { gsub(/:/, " ", $3) ; print $3 } }' < /proc/net/tcp) ; do
echo $STR ; done | sed 's/^\(..\)\(..\)\(..\)\(..\)$/0x\4 0x\3 0x\2 0x\1\n/g;s/^\(..\)\(..\)$/0x\1\2/g') ; done
0x0A 0xB6 0x49 0x1B 0xD1AF
# Convert hex to decimal and add colon before port
$ printf '%d.%d.%d.%d:%d\n' $(for STR in $(awk '{ if ($10 == 666374737 \
&& $2~/:01BB$/ ) { gsub(/:/, " ", $3) ; print $3 } }' < /proc/net/tcp) ; do
echo $STR ; done | sed 's/^\(..\)\(..\)\(..\)\(..\)$/0x\4 0x\3 0x\2 0x\1\n/g;s/^\(..\)\(..\)$/0x\1\2/g')
10.182.73.27:53679
# There you have it:
# Get remote IP:port of client connecting to local port 443 ( hex 0x01BB) on given PID $PID
$ printf '%d.%d.%d.%d:%d\n' $(for SOCKET in $(ls -l /proc/$PID/fd/ \
| grep socket | grep -o '\[.*\]' | sed 's/\[//;s/\]//' ) ; do
echo $(for STR in $(awk '{ if ($10 == '$SOCKET' && $2~/:01BB$/ ) \
{ gsub(/:/, " ", $3) ; print $3 } }' < /proc/net/tcp) ; do echo $STR ; done
| sed 's/^\(..\)\(..\)\(..\)\(..\)$/0x\4 0x\3 0x\2 0x\1\n/g;s/^\(..\)\(..\)$/0x\1\2/g') ; done)
10.182.73.27:53679
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment