2

I have a specific need to identify which interface a part of an octet (e.g. xx.xx.xx.112) belongs to on a CentOS machine

My initial idea was to dump the output of ifconfig and parse it manually to identify the corresponding interface. Is it the right approach or a better way exists to do this?

My crude attempt would be something like below in GNU grep,

ifconfig | grep -B1 -E '\.112' | grep -oP 'e\w+:'

1 Answer 1

3

I think an awk answer might be slightly quicker since it won't need the extra subshells:

ip addr show | awk -F: '/^[0-9]/ {dev=$2} /inet .*\.112/ {print dev; exit}'

Another possibility, if you know an address that would be routed out the interface, like assuming there's a gateway at the .1 address you could do

ip route get a.b.c.1 | cut -f3 -d' '

In general ip is the newer command that is supposed to replace ifconfig, though that's been true for a long time now and ifconfig isn't gone yet, but see this Server Fault question about the topic.

4
  • Thanks for the answer. You might want to re-check the the input field separator, I guess it is un-terminated. Can you fix it please?
    – Inian
    Mar 14, 2017 at 12:05
  • @Inian Oops, sorry for bad copy-paste, I fixed it to have the missing colon. FWIW this is done on a centos 6 box, your output might be slightly different if you have a different version Mar 14, 2017 at 12:06
  • Yup, it is working now. I was able to fix it myself, but my biggest concern apart from this would be, if this is the right approach (parsing output of ifconfig) to identify an interface for an IP? Would this be effective?
    – Inian
    Mar 14, 2017 at 12:24
  • 1
    @Inian well, aside from the recommendation to switch to ip instead of ifconfig I don't think this is philosophically a bad approach, and I expect that it will indeed be effective. Of course, depending on what you're trying to do in the end there may be other ways to accomplish that goal Mar 14, 2017 at 12:28

You must log in to answer this question.

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