linux 查看第一个ip,linux – 如何从ifconfig命令捕获第一个IP地址?

如何捕获来自ifconfig命令的第一个IP地址?

ifconfig -a

enw178032: flags=4163 mtu 1500

inet 100.14.22.12 netmask 255.255.0.0 broadcast 100.14.255.255

inet6 fe80::250:56ff:fe9c:158a prefixlen 64 scopeid 0x20

ether 00:10:56:9c:65:8a txqueuelen 1000 (Ethernet)

RX packets 26846250 bytes 12068811576 (11.2 GiB)

RX errors 0 dropped 58671 overruns 0 frame 0

TX packets 3368855 bytes 1139160934 (1.0 GiB)

TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

预期结果:

IP=100.14.22.12

解决方法:

最好避免使用ifconfig在脚本中获取IP地址,但在某些发行版中不推荐使用它(例如CentOS和其他版本,不再默认安装它).

在其他系统中,ifconfig的输出根据分发的发布而变化(例如,ifconfig的输出/间隔/字段与Debian 8不同,例如Debian 9).

要使用ip获取IP地址,请以类似的方式询问:

ip addr | awk ' !/127.0.0.1/ && /inet/ { gsub(/\/.*/, "", $2); print "IP="$2 } '

或者更好的是:

$ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '

192.168.1.249

或者,当你问“IP =”时

#!/bin/bash

echo -n "IP="

ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '

从@Roman无耻地改编这个想法

$ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print "IP="$4 } '

IP=192.168.1.249

正常输出:

$ip -o -4 address show

1: lo inet 127.0.0.1/8 scope host lo\ valid_lft forever preferred_lft forever

2: eth0 inet 192.168.1.249/24 brd 192.168.1.255 scope global eth0\ valid_lft forever preferred_lft forever

来自man ip:

-o, -oneline

output each record on a single line, replacing line feeds with

the ‘\’ character. This is convenient when you want to count

records with wc(1) or to grep(1) the output.

ifconfig is from net-tools, which hasn’t been able to fully keep up

with the Linux network stack for a long time. It also still uses ioctl

for network configuration, which is an ugly and less powerful way of

interacting with the kernel.

Around 2005 a new mechanism for controlling the network stack was

introduced – netlink sockets.

To configure the network interface iproute2 makes use of that

full-duplex netlink socket mechanism, while ifconfig relies on an

ioctl system call.

标签:bash,linux,awk,sed,ifconfig

来源: https://codeday.me/bug/20190809/1630303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值