tags:

views:

81

answers:

6

When I tried ifconfig it gives me the whole all the information regarding the Network Adapter.

I tried :

system( "ifconfig -a | grep inet | "
          "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
          " > address.txt" ) ;

which output two Ips :

  inet  addr:17.24.17.229
  inet  addr:127.0.0.1

But I need just the 1st one , How can I filter this out.

+2  A: 

You might use head but...

I might be mistaking of course, but my guess is that you don't really need the first one.

You're probably looking for the one that is connected to the gateway (or the Internet).

As far as I know, the order of the IP addresses or interfaces is unspecified.

What do you want to achieve exactly ?

If you want to know what interface is "connected to the internet", a more reliable approach is to find the interface which has the default route (using route) then to use ifconfig <interface> to directly get the correct IP address.

ereOn
Not an answer but very good point. +1 ` ` ` `
Pekka
however maybe the complexity of this is lost on this user, as I just noticed I asked him the same thing in his [last question](http://stackoverflow.com/questions/3997428/how-can-i-get-the-ip-address-of-system) :)
Pekka
@Pekka: So did I, actually ;)
ereOn
@Pekka: Great point - tried the OP's script, and lo and behold, the loopback was on the first line. Not a very useful interface, that. So I grepped that out, and the management network interface came up next. Not useful either. Next, the bridge interface for my VMs. Uh-oh. Wouldn't it be more useful to check the output of `route`? It does have the default gateway there.
Piskvor
@Piskvor that sounds like a good idea! The OP needs to clarify what he really needs.
Pekka
@Piskvor: I just added a suggestion to use `route` as well. That's also how I usually do.
ereOn
A: 

Don't look at all of the adapters, just the one you want.

system( "ifconfig -a eth0 | grep inet | "
          "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
          " > address.txt" ) ;
Andrew Sledge
A: 

you can reduce the use of grep and head

ifconfig -a | sed -nr -e '/inet\b/{s|^.*inet\s+addr:(.[^ \t]*).*|\1|;h}' -e '${x;p}'
ghostdog74
A: 

I'd use iproute2's ip:

ip -o addr show dev eth0 | while read IFNUM IFNAME ADDRTYPE ADDR REST; do [ "$ADDRTYPE" == "inet" ] && echo $ADDR; done
9.87.65.43/21

(Not only because it's easier to parse, but it'll also show e.g. secondary IPs, which ifconfig can't.)

al
A: 

If the output of ifconfig or ip ever changes, your program will break.

Why not not just use the SIOCGIFCONF ioctl() and get it directly from the source?

ETA: It's also unsafe to assume that any given system will have just one loopback interface and just one Ethernet with a single address.

Blrfl
A: 

How about 'ifconfig eth0'?

Chris