We have multihomed servers. And to simplify things, I would like to know the dns of the interface trough which I'm logged in. (e.g. to set PS1 thus it can be used in scp commands)

My solution for that problems seems to be rather complicated. => is there a easier/simpler and more portable way?

ORIGIN_NAME=`who -m | cut -d\( -f2 | cut -d\) -f1`
ORIGIN_IP=`getent hosts $ORIGIN_NAME | awk '{ print $1; }'`
INTERFACE_NAME=`ip route get $ORIGIN_IP | grep dev | awk '{ print substr($0,index($0,"dev")+4,4); }'`
INTERFACE_IP=`ifconfig -a $INTERFACE_NAME | grep inet | awk ' { print $2; }' | cut -d: -f2`
getent hosts $INTERFACE_IP | awk '{ print $NF; }'
  • How do you use the name of the ethernet device in for example scp ?
    – user9517
    Aug 17 '16 at 17:52
  • If I have to copy something to a server and I'm already logged in! (network pathes are pretty different in different zones, thus I'm always unsure, which is the right interface to use...)
    – Thomas SV
    Aug 17 '16 at 18:08
  • I'm using putty to log in (using predefined sessions), but pscp.exe to copy files. Maybe, that's the mistake :) But currently, it's useful to have the used interface in the PS1 prompt
    – Thomas SV
    Aug 17 '16 at 18:11
  • Argh... "name of the interface" is misleading! That would be e.g. "eth0". What I'm obviously searching for is the dns of the IP mapped to the interface I have used to reach the server!
    – Thomas SV
    Aug 17 '16 at 18:14
  • 1
    There is no guarantee that there will be a PTR (or similar host) record that will give the name related to the ip address.
    – user9517
    Aug 17 '16 at 18:27

@Mark Plotnick has the easiest one! Just use echo $SSH_CONNECTION it will output something like client-IP, client-Port, server-IP, server-port the first is your IP (from where you login) the second is the IP or host you are connected to. Credit should go to Mark on this one.

  • Thanks! Credit should go to Mark, but he just answered in a comment... Please correct your answer: the fields are: client-IP, client-Port, server-IP, server-port. Thx to you both!
    – Thomas SV
    Aug 18 '16 at 8:30
ip route get ${SSH_CONNECTION%% *}
  • ip route get is unneccessary, since SSH_CONNECTION already contains the IP of the used Interface on the Server side
    – Thomas SV
    Aug 18 '16 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.