an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:
sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
sshloop=1
else
sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
[ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
fi
done
this method is compatible with direct ssh, sudoed users, and screen sessions. it will trail up through the process tree until it finds a pid with the SSH_CLIENT variable, then record its IP as $sshClientIP. if it gets too far up the tree, it will record the IP as 'localhost' and leave the loop.