简体   繁体   English

使用 Bash 解析 ifconfig 以获取当前 IP 地址(wifi 或以太网)

[英]Parse ifconfig with Bash to get current IP address (wifi or ethernet)

I'm trying to output my current IP address using a bash script.我正在尝试使用 bash 脚本输出我当前的 IP 地址。 I'm trying to wrap my head around awk and managed the following:我正在尝试围绕awk并管理以下内容:

/sbin/ifconfig $1 | grep "inet" | awk '$1 == "inet" {gsub(/\/.$/, "", $2); print $2}'

which outputs:输出:

127.0.0.1
192.168.178.57

I have two issues now: First of all, 127.0.0.1 is useless, how do I get rid of it?我现在有两个问题:首先, 127.0.0.1没用,怎么去掉? Secondly, 192.168.178.57 is the IP address of my Wi-Fi connection.其次, 192.168.178.57是我的 Wi-Fi 连接的 IP 地址。 However I'd like the script to be able to grab the IP address of either Wi-Fi or Ethernet, whichever one I'm using at the moment.但是,我希望脚本能够获取 Wi-Fi 或以太网的 IP 地址,无论我目前使用的是哪种。 A sample output from /sbin/ifconfig can be found here.可以在此处找到/sbin/ifconfig示例输出

你可以使用这个 awk 脚本:

awk '/inet / && $2 != "127.0.0.1"{print $2}' <(ifconfig)

Best way to get current used IP on a computer.在计算机上获取当前使用的 IP 的最佳方法。

ip route get 8.8.8.8 | awk '{print $NF;exit}'
192.168.1.30

OLD VERSION.旧版本。 DO NOT USE!!!!!!不使用!!!!!!

See my reply to this post: Linux bash script to extract IP address看我对这个帖子的回复: Linux bash script to extract IP address

I would suggest you to use ip command instead of ifconfig as ip is the "future" and more reliable when compared to ifconfig .我建议您使用ip命令而不是ifconfig因为ip是“未来”,与ifconfig相比更可靠。

$ ip addr show dev $(ip route ls|awk '/default/ {print $5}')|grep -Po 'inet \K(\d{1,3}\.?){4}'
10.251.26.9

Here this oneliner will which the default interface using the ip route ls command and gather the interface id and based on it the IP address of that interface will be grepped.在这里,这个 oneliner 将使用ip route ls命令默认接口并收集接口 id,并基于它来 grepped 该接口的 IP 地址。

Here the grep command uses regex to get the IP address safely.这里grep命令使用正则表达式来安全地获取IP地址。

If you don't mind installing something and/or if you already have node, try sindresorhus/internal-ip如果您不介意安装某些东西和/或如果您已经有节点,请尝试sindresorhus/internal-ip

$ npm install --global internal-ip
$ internal-ip
192.168.0.2

Pro: cross-platform优点:跨平台

Note: I know it's not bash and that it doesn't use ifconfig , but I got here looking for a generic tool to use anywhere, perhaps it can help others.注意:我知道它不是 bash 并且它不使用ifconfig ,但是我来到这里寻找可以在任何地方使用的通用工具,也许它可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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