Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I'm wondering if it's possible to dynamically read in the IP addresses of network interfaces for use in a bash script. Something like:

#!/bin/bash
MYPUBLICIP= get_eth0_address
MYPRIVATEIP= get_eth0:0_address
  • How would I go about this?
  • Is it possible to distinguish between eth0 and the virtual eth0:0?

[Background] I'm trying to write a script to apply various rules to iptables for a set of VPSs. I'm trying to avoid having to fiddle around with the individual IPs of each machine.

share|improve this question
    
You should be able to make your own function, using stackoverflow.com/questions/1452917/…. Or stackoverflow.com/questions/12474172/… –  Isaac Apr 25 '13 at 8:59

2 Answers 2

up vote 5 down vote accepted

ip will always return all the address records for a physical interface, even if you specify a virtual one.

ifconfig let's you specify a single interface, but is a bit more annoying to parse:

ifconfig eth0:0 |awk -F':| ' '/inet addr/{print $13}'

EDIT

The ip way can be managed with more selective awk, of course:

ip -o -4 addr sh |awk '/eth0:0/{print $4}'
share|improve this answer
    
Ah, great thanks. –  UpTheCreek Apr 25 '13 at 9:30
    
(Please accept the answer if it works out for you) –  SmallClanger Apr 25 '13 at 11:03

Something like

ip -4 -o addr show dev eth0 | sed 's/\// /g' | awk '{print $4}'

should give you the bare ip address of the relevant interface.

share|improve this answer
    
Interesting - I'll have a play around with that. Thanks. –  UpTheCreek Apr 25 '13 at 9:01
    
It seems it returns both IP addresses assigned to the interface whether I use eth0 or eth0:0. If the order is guaranteed though, perhaps I can just select the right one from the string. –  UpTheCreek Apr 25 '13 at 9:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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