简体   繁体   中英

How do I get the IP of only one Interface

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.

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.

你可以减少使用grephead

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

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" ) ;

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 eg secondary IPs, which ifconfig can't.)

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.

'ifconfig eth0'怎么样?

hostname -I | awk '{print $1}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM