哪个终端命令只获取 IP 地址而不获取其他内容?

发布于 2024-12-21 20:31:01 字数 106 浏览 1 评论 0原文

我试图在我编写的脚本中仅使用 IP 地址 (inet) 作为参数。

在unix终端中是否有一种简单的方法可以只获取IP地址,而不是通过ifconfig查找?

I'm trying to use just the IP address (inet) as a parameter in a script I wrote.

Is there an easy way in a unix terminal to get just the IP address, rather than looking through ifconfig?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

残花月 2024-12-28 20:31:01

您可以编写一个仅返回 IP 的脚本,例如:

/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'

对于 MAC:

ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2

或者对于 linux 系统

hostname -i | awk '{print $3}' # Ubuntu 

hostname -i # Debian

You can write a script that only return the IP like:

/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'

For MAC:

ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2

Or for linux system

hostname -i | awk '{print $3}' # Ubuntu 

hostname -i # Debian
君勿笑 2024-12-28 20:31:01

这将为您提供所有 IPv4 接口,包括环回 127.0.0.1:

ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

这将仅显示 eth0

ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

这样您可以获得 IPv6 地址:

ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'

eth0 IPv6:

ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'

This will give you all IPv4 interfaces, including the loopback 127.0.0.1:

ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

This will only show eth0:

ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

And this way you can get IPv6 addresses:

ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'

Only eth0 IPv6:

ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'
回梦 2024-12-28 20:31:01

一般来说,永远不能保证一个系统只有一个 IP 地址,例如,您可以同时拥有以太网和 WLAN 连接,如果您有活动的 VPN 连接,那么您将拥有更多的 IP 地址。

Linux

在 Linux 上,hostname -I 将列出当前的 IP 地址。在某些情况下,依赖它总是只返回一个 IP 地址很可能无法按预期工作,因此一种更可靠的方法是将结果转换为数组,然后循环遍历元素:

ips=($(hostname -I))

for ip in "${ips[@]}"
do
    echo $ip
done

注意:如果 hostname -I 返回 IPv4 和 IPv6 格式的 IP,那么您可以使用 hostname -I |剪切 -f1 -d' ' 仅显示 IPv4 IP。

OSX

在 OSX 上,如果您知道接口,您可以使用:

~$ ipconfig getifaddr en0
# OUTPUT: 192.168.1.123

它将返回 IP 地址。

要动态检测 MacOS 上的(第一个)活动网络接口:

network_device=$(scutil --dns |awk -F'[()]' '$1~/if_index/ {print $2;exit;}')
ip=$(ipconfig getifaddr "$network_device")
echo $ip
### OUTPUT: 192.168.1.123 

获取外部 IP

要获取外部 IP,您可以查询文本模式服务,例如 curl https://ipecho.net/plain将返回纯文本外部 IP。

据称更快的方法可能是查询已知的 DNS 服务器,例如:

dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short

Generally, it is never guaranteed that a system will only have one IP address, for example, you can have both an ethernet and wlan connections, and if you have active VPN connections then you'll have yet more IP addresses.

Linux

On Linux, hostname -I will list the current IP address(es). Relying on it always returning just one IP address will most likely not work as expected under some scenarios, so a more reliable way would be converting the result to an array and then loop over the elements:

ips=($(hostname -I))

for ip in "${ips[@]}"
do
    echo $ip
done

Note: If hostname -I returns the IP both in IPv4 and IPv6 formats then you can use instead hostname -I | cut -f1 -d' ' to only show the IPv4 IP.

OSX

On OSX, if you know the interface, you could use:

~$ ipconfig getifaddr en0
# OUTPUT: 192.168.1.123

which will return just the IP address.

To detect dynamically the (first) active network interface on MacOS:

network_device=$(scutil --dns |awk -F'[()]' '$1~/if_index/ {print $2;exit;}')
ip=$(ipconfig getifaddr "$network_device")
echo $ip
### OUTPUT: 192.168.1.123 

Getting the external IP

To get the external IP you could query a text-mode service, for example curl https://ipecho.net/plain would return a plain text external IP.

A supposedly faster approach could be to query a known DNS server, e.g.:

dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short
金橙橙 2024-12-28 20:31:01
hostname -I  

该命令将为您提供 Ubuntu 中所需的确切 IP 地址。请注意,该标志是大写

hostname -I  

This command will give you the exact IP address as you want in Ubuntu. Note the flag is uppercase.

不羁少年 2024-12-28 20:31:01

在最新的 Ubuntu 版本(14.04 - 16.04)上,这个命令对我来说很有效。

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

On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.

hostname -I | awk '{print $1}'
愁以何悠 2024-12-28 20:31:01

要仅获取 Mac OS X 上的 IP 地址,您可以键入以下命令:

ipconfig getifaddr en0

To get only the IP address on Mac OS X you can type the following command:

ipconfig getifaddr en0
雾里花 2024-12-28 20:31:01

我不喜欢在脚本中使用 awk 等。ip 可以选择以 JSON 格式输出。

如果省略 $interface 那么您将获得所有 IP 地址:

ip -json addr show $interface | \
  jq -r '.[] | .addr_info[] | select(.family == "inet") | .local'

I prefer not to use awk and such in scripts.. ip has the option to output in JSON.

If you leave out $interface then you get all of the ip addresses:

ip -json addr show $interface | \
  jq -r '.[] | .addr_info[] | select(.family == "inet") | .local'
舞袖。长 2024-12-28 20:31:01

如果你的环境有限,可以使用这个命令:

ip -4 addr show dev eth0 | grep inet | tr -s " " | cut -d" " -f3 | head -n 1

If you have limited environment, you may use this command:

ip -4 addr show dev eth0 | grep inet | tr -s " " | cut -d" " -f3 | head -n 1
是伱的 2024-12-28 20:31:01

ip -4 addr show eth0 在某些机器上不起作用。例如,我收到此错误:
ip:符号查找错误:ip:未定义符号:bpf_program__section_name,版本LIBBPF_0.2.0

这对我有用:

/sbin/ifconfig eth0 | grep 'inet ' | awk '{ print $2}'

这比接受的答案少了一个管道。此外,我的 ifconfig 输出没有 inet addr

要获取 IPv6 地址,请使用以下命令:

/sbin/ifconfig eth0 | grep 'inet6 ' | awk '{ print $2}'

ip -4 addr show eth0 doesn't work on some machines. For example, I get this error:
ip: symbol lookup error: ip: undefined symbol: bpf_program__section_name, version LIBBPF_0.2.0

This works for me:

/sbin/ifconfig eth0 | grep 'inet ' | awk '{ print $2}'

This has one less pipe than the accepted answer. In addition, my ifconfig output does not have inet addr.

To get the IPv6 address, use this:

/sbin/ifconfig eth0 | grep 'inet6 ' | awk '{ print $2}'
小女人ら 2024-12-28 20:31:01

命令 ifconfig 已弃用,您应该在 Linux 上使用 ip 命令。

另外,ip a 将为您提供与 IP 位于同一行的范围,因此更易于使用。

此命令将显示您的全局(外部)IP:

ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'

所有 IPv4(也为 127.0.0.1):

ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'

所有 IPv6(也为 ::1):

ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'

Command ifconfig is deprected and you should use ip command on Linux.

Also ip a will give you scope on the same line as IP so it's easier to use.

This command will show you your global (external) IP:

ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'

All IPv4 (also 127.0.0.1):

ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'

All IPv6 (also ::1):

ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'
半葬歌 2024-12-28 20:31:01

我想要一些简单的东西作为 Bash 别名。我发现 hostname -I 最适合我(hostname v3.15)。由于某种原因,hostname -i 返回环回 IP,但是 hostname -I 为我提供了 wlan0 的正确 IP,并且无需通过 grep 或 awk 进行管道输出。一个缺点是,如果您有多个 IP,hostname -I 将输出所有 IP。

I wanted something simple that worked as a Bash alias. I found that hostname -I works best for me (hostname v3.15). hostname -i returns the loopback IP, for some reason, but hostname -I gives me the correct IP for wlan0, and without having to pipe output through grep or awk. A drawback is that hostname -I will output all IPs, if you have more than one.

双手揣兜 2024-12-28 20:31:01

似乎很少有答案使用较新的 ip 命令(替换 ifconfig),因此这里是使用 ip addrgrep< /code> 和 awk 来简单地打印与 wlan0 接口关联的 IPv4 地址:

ip addr show wlan0|grep inet|grep -v inet6|awk '{print $2}'|awk '{split($0,a,"/"); print a[1]}'

虽然不是最紧凑或最奇特的解决方案,但它(可以说)很容易理解(请参阅下面的解释)并为其他目的进行修改,例如获取 MAC 地址的最后 3 个八位字节,如下所示:

ip addr show wlan0|grep link/ether|awk '{print $2}'|awk '{split($0,mac,":"); print mac[4] mac[5] mac[6]}'

说明: ip addr show wlan0 输出与名为 wlan0 的网络接口关联的信息,应该与此类似:

4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether dc:a6:32:04:06:ab brd ff:ff:ff:ff:ff:ff
    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
       valid_lft forever preferred_lft forever
    inet6 fe80::d340:5e4b:78e0:90f/64 scope link 
       valid_lft forever preferred_lft forever

接下来 grep inet 过滤掉不包含“inet”的行(IPv4 和 IPv6 配置),并且 grep -v inet6 过滤掉剩余的行do 包含“inet6”,这应该会产生如下所示的单行:

    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0

最后,第一个 awk 提取“172.18.18.1/24”字段,第二个删除网络掩码简写,仅保留 IPv4 地址。

另外,我认为值得一提的是,如果您正在编写脚本,那么通常有许多更丰富和/或更强大的工具来获取此信息,您可能想使用这些工具。例如,如果使用 Node.js,则有 ipaddr-linux,如果使用 Ruby,则有 linux-ip-parser等。

另请参阅https://unix.stackexchange.com/questions/119269/how-使用 shell 脚本获取 ip 地址

Few answers appear to be using the newer ip command (replacement for ifconfig) so here is one that uses ip addr, grep, and awk to simply print the IPv4 address associated with the wlan0 interface:

ip addr show wlan0|grep inet|grep -v inet6|awk '{print $2}'|awk '{split($0,a,"/"); print a[1]}'

While not the most compact or fancy solution, it is (arguably) easy to understand (see explanation below) and modify for other purposes, such as getting the last 3 octets of the MAC address like this:

ip addr show wlan0|grep link/ether|awk '{print $2}'|awk '{split($0,mac,":"); print mac[4] mac[5] mac[6]}'

Explanation: ip addr show wlan0 outputs information associated with the network interface named wlan0, which should be similar to this:

4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether dc:a6:32:04:06:ab brd ff:ff:ff:ff:ff:ff
    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
       valid_lft forever preferred_lft forever
    inet6 fe80::d340:5e4b:78e0:90f/64 scope link 
       valid_lft forever preferred_lft forever

Next grep inet filters out the lines that don't contain "inet" (IPv4 and IPv6 configuration) and grep -v inet6 filters out the remaining lines that do contain "inet6", which should result in a single line like this one:

    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0

Finally, the first awk extract the "172.18.18.1/24" field and the second removes the network mask shorthand, leaving just the IPv4 address.

Also, I think it's worth mentioning that if you are scripting then there are often many richer and/or more robust tools for obtaining this information, which you might want to use instead. For example, if using Node.js there is ipaddr-linux, if using Ruby there is linux-ip-parser, etc.

See also https://unix.stackexchange.com/questions/119269/how-to-get-ip-address-using-shell-script

耶耶耶 2024-12-28 20:31:01

要仅打印 eth0 的 IP 地址,而不显示其他文本:

ifconfig eth0 | grep -Po '(?<=inet addr:)[\d.]+'

要确定您的主接口(因为它可能不是“eth0”),请使用:

route | grep ^default | sed "s/.* //"

上述两行可以组合成一个命令,例如这:

ifconfig `route | grep ^default | sed "s/.* //"` \
  | grep -Po '(?<=inet addr:)[\d.]+'

To print only the IP address of eth0, without other text:

ifconfig eth0 | grep -Po '(?<=inet addr:)[\d.]+'

To determine your primary interface (because it might not be "eth0"), use:

route | grep ^default | sed "s/.* //"

The above two lines can be combined into a single command like this:

ifconfig `route | grep ^default | sed "s/.* //"` \
  | grep -Po '(?<=inet addr:)[\d.]+'
深爱成瘾 2024-12-28 20:31:01

ip adddr,简短方式

ip -4 -br addr show enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1

或将

ip -4 -br 缩短为 enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1

必须在大多数现代 Linux 发行版中工作

ip adddr, the short way

ip -4 -br addr show enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1

or shorten

ip -4 -br a s enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1

must work in most modern Linux distribution

披肩女神 2024-12-28 20:31:01

Ubuntu(和 Debian 等发行版)上,

要仅获取本地地址数字,请执行以下命令:

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

有关网络接口配置和全局 IP 地址使用的全面信息:

curl -4 icanhazip.com
curl  ifconfig.co //this responds faster

要深入了解任何 IP 地址(包括您自己的 IP 地址)的奥秘:

 whois $(curl ifconfig.co)   

确保您安装了 whois 工具。如果没有,只需执行:

sudo apt-get install whois

On Ubuntu( and Debian like distro)

To obtain just the local address digits, execute the following command:

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

For a comprehensive picture of your network interface configuration and global IP address use:

curl -4 icanhazip.com
curl  ifconfig.co //this responds faster

To dive deeper into the mysteries of any IP address (including your own):

 whois $(curl ifconfig.co)   

Ensure you have the whois tool installed. If not, simply execute:

sudo apt-get install whois
一口甜 2024-12-28 20:31:01

这在 Mac 上就可以解决问题:

ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')

在我的机器上解析到 ping 192.168.1.2

专业提示$(...) 表示在子 shell 中运行括号内的任何内容并将其作为值返回。

That would do the trick in a Mac :

ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')

That resolved to ping 192.168.1.2 in my machine.

Pro tip: $(...) means run whatever is inside the parentheses in a subshell and return that as the value.

夕色琉璃 2024-12-28 20:31:01

我们只需使用 2 个命令 ( ifconfig + awk ) 即可获取我们想要的 IP (v4),如下所示:

在 Linux 上,假设从 eth0 接口获取 IP 地址,请运行以下命令

/sbin/ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'

: OSX,假设从 en0 接口获取 IP 地址,运行以下命令:

/sbin/ifconfig en0 | awk '/inet /{print $2}'

要知道我们的公共/外部 IP,请在 ~/.bashrc 中添加此函数

whatismyip () {
    curl -s "http://api.duckduckgo.com/?q=ip&format=json" | jq '.Answer' | grep --color=auto -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
}

,然后运行, whatismyip

We can simply use only 2 commands ( ifconfig + awk ) to get just the IP (v4) we want like so:

On Linux, assuming to get IP address from eth0 interface, run the following command:

/sbin/ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'

On OSX, assumming to get IP adddress from en0 interface, run the following command:

/sbin/ifconfig en0 | awk '/inet /{print $2}'

To know our public/external IP, add this function in ~/.bashrc

whatismyip () {
    curl -s "http://api.duckduckgo.com/?q=ip&format=json" | jq '.Answer' | grep --color=auto -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
}

Then run, whatismyip

極樂鬼 2024-12-28 20:31:01

我总是在最意想不到的时候需要这个,而且毫无疑问,最终会在 SO 上搜索这样的线程。所以我写了一个简单的脚本来通过netstat获取IPv4地址,名为echoip - 你可以找到它在这里。网络地址的 bash 看起来像这样,它还从 ipecho.net 获取您的公共地址:

IPV4='\d+(\.\d+){3}'
INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`

for i in "${!INTERFACES[@]}"; do
  printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
done

echoip 脚本产生如下输出:

$ echoip
public: 26.106.59.169
en0:    10.1.10.2

I always wind up needing this at the most unexpected times and, without fail, wind up searching for threads like this on SO. So I wrote a simple script to get IPv4 addresses via netstat, called echoip - you can find it here. The bash for network addresses looks like this, it also gets your public address from ipecho.net:

IPV4='\d+(\.\d+){3}'
INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`

for i in "${!INTERFACES[@]}"; do
  printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
done

The echoip script yields an output like this:

$ echoip
public: 26.106.59.169
en0:    10.1.10.2
傲性难收 2024-12-28 20:31:01

man hostname 中,有更简单的方法,可以自动排除环回 IP,并仅显示所有分配给主机 IP 地址的空格分隔列表:

root@srv:~# hostname --all-ip-addresses
11.12.13.14 192.168.15.19 

root@srv:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
   inet 127.0.0.1/8 scope host lo
   inet6 ::1/128 scope host 
   valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN 
  link/void 
  inet 11.12.13.14/32 scope global venet0:0
  inet 192.168.15.19/32 scope global venet0:1

In man hostname there is even more easier way which automatically excluding loopback IP and showing only space separated list of all assigned to host ip addresses:

root@srv:~# hostname --all-ip-addresses
11.12.13.14 192.168.15.19 

root@srv:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
   inet 127.0.0.1/8 scope host lo
   inet6 ::1/128 scope host 
   valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN 
  link/void 
  inet 11.12.13.14/32 scope global venet0:0
  inet 192.168.15.19/32 scope global venet0:1
卷耳 2024-12-28 20:31:01

默认路由的 IPv4 地址:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"

默认路由的 IPv6 地址:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet6 )[^ /]+"

这些仅需要命令 ipgrep,并支持 -P 和<代码>-o。 head -1 是必需的,因为当系统具有足够复杂的网络设置时,ip Route 可能会显示多个默认路由。

如果你不介意哪个IP是哪个,你可以这样做

ip route | grep -Po '(?<=src )[^ ]+'

hostname --all-ip-addresses

The IPv4 address for the default route:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"

The IPv6 address for the default route:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet6 )[^ /]+"

These only require commands ip and grep with support for -P and -o. The head -1 is required because ip route may show multiple default routes when system has complex enough network setup.

If you don't mind which IP is which, you can just do

ip route | grep -Po '(?<=src )[^ ]+'

or

hostname --all-ip-addresses
十年不长 2024-12-28 20:31:01

最简单的方法是 Mikko 所说的

hostname --all-ip-addresses

输出

您也可以这样做以获得更多细节:

ip route

输出
输入图片此处描述

the easiest way is as Mikko said

hostname --all-ip-addresses

the output
enter image description here

you can also do that for little more details :

ip route

the output
enter image description here

红玫瑰 2024-12-28 20:31:01

使用以下命令:

/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '

Use the following command:

/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '
零崎曲识 2024-12-28 20:31:01

这是我的版本,您可以在其中传递按优先级排序的接口列表:

getIpFromInterface()
{
    interface=$1
    ifconfig ${interface}  > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}

getCurrentIpAddress(){
    IFLIST=(${@:-${IFLIST[@]}})
    for currentInterface in ${IFLIST[@]}
    do
        IP=$(getIpFromInterface  $currentInterface)
        [[ -z "$IP" ]] && continue
    echo ${IP/*:}
    return
    done
}

IFLIST=(tap0 en1 en0)
getCurrentIpAddress $@

因此,如果我连接了 VPN、Wifi 和以太网,我的 VPN 地址(在接口 tap0 上)将被返回。该脚本适用于 linux 和 osx,如果您想覆盖 IFLIST,则可以接受参数。

请注意,如果您想使用 IPV6,则必须将 'inet' 替换为 'inet6'。

Here is my version, in which you can pass a list of interfaces, ordered by priority:

getIpFromInterface()
{
    interface=$1
    ifconfig ${interface}  > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}

getCurrentIpAddress(){
    IFLIST=(${@:-${IFLIST[@]}})
    for currentInterface in ${IFLIST[@]}
    do
        IP=$(getIpFromInterface  $currentInterface)
        [[ -z "$IP" ]] && continue
    echo ${IP/*:}
    return
    done
}

IFLIST=(tap0 en1 en0)
getCurrentIpAddress $@

So if I'm connected with VPN, Wifi and ethernet, my VPN address (on interface tap0) will be returned. The script works on both linux and osx, and can take arguments if you want to override IFLIST

Note that if you want to use IPV6, you'll have to replace 'inet ' by 'inet6'.

旧城空念 2024-12-28 20:31:01

使用这一行脚本:
<代码>
ifconfig | grep “inet”| grep -v 127.0.0.1|awk '匹配($0, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/) {打印substr($0,RSTART,RLENGTH)}'

麦克& linux(在ubuntu中测试)都可以。

use this one line script:

ifconfig | grep "inet " | grep -v 127.0.0.1|awk 'match($0, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/) {print substr($0,RSTART,RLENGTH)}'

mac & linux (tested in ubuntu) both works.

柏拉图鍀咏恒 2024-12-28 20:31:01

您还可以使用以下命令:

ip route | grep src

注意:只有当您连接到互联网时,此命令才有效。

You can also use the following command:

ip route | grep src

NOTE: This will only work if you have connectivity to the internet.

我们的影子 2024-12-28 20:31:01

还有另一种方法可以做到这一点。

我经常需要检查各种接口的 IP(例如 eth0、隧道等),

所以我是这样做的:

ip -4 -br a | awk '{print $1,$3}'

输出:

$ ip -4 -br a | awk '{print $1,$3}'
lo 127.0.0.1/8
eth0 192.168.0.248/24
tun0 192.168.119.1

如果您不关心网络适配器,只需从 awk 命令中删除 $1 即可。

ip -4 -br a | awk '{print $3}'   
127.0.0.1/8
192.168.0.248/24
192.168.119.124/24

为了简单起见,我只需将其添加为别名(记住转义 $!)

$ alias me="ip -4 -br a | awk '{print \$1,\$3}'" 
                                                                                                                              
$ me                                            
lo 127.0.0.1/8
eth0 192.168.0.248/24
tun0 192.168.119.124/24

yet another way to do it.

I often need to check the IP of various interfaces (e.g eth0, tunnel, etc.)

So this is how i do it:

ip -4 -br a | awk '{print $1,$3}'

output:

$ ip -4 -br a | awk '{print $1,$3}'
lo 127.0.0.1/8
eth0 192.168.0.248/24
tun0 192.168.119.1

If you do not care about the network adapter, just remove the $1 from awk command.

ip -4 -br a | awk '{print $3}'   
127.0.0.1/8
192.168.0.248/24
192.168.119.124/24

to make it easy, i just add it as an alias (remember to escape the $'s!)

$ alias me="ip -4 -br a | awk '{print \$1,\$3}'" 
                                                                                                                              
$ me                                            
lo 127.0.0.1/8
eth0 192.168.0.248/24
tun0 192.168.119.124/24
差↓一点笑了 2024-12-28 20:31:01

我没有看到 nmcli 的任何答案,它是一个用于控制 NetworkManager 的命令行工具。

所以就在这里 :)

wolf@linux:~$ nmcli device 
DEVICE  TYPE      STATE        CONNECTION 
eth1    ethernet  unavailable  --         
eth0    ethernet  unmanaged    --         
lo      loopback  unmanaged    --         
wolf@linux:~$ 

如果您想从特定网络接口获取信息(在本例中为 lo),

wolf@linux:~$ nmcli device show lo
GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
GENERAL.STATE:                          10 (unmanaged)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --
IP4.ADDRESS[1]:                         127.0.0.1/8
IP4.GATEWAY:                            --
IP4.ROUTE[1]:                           dst = 127.0.0.0/8, nh = 0.0.0.0,>
IP4.ROUTE[2]:                           dst = 127.0.0.1/32, nh = 0.0.0.0>
IP6.ADDRESS[1]:                         ::1/128
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = ::1/128, nh = ::, mt = 256
IP6.ROUTE[2]:                           dst = ::1/128, nh = ::, mt = 0, >
wolf@linux:~$ 

但由于您只想获取 IP 地址,只需将输出发送到 grepcutawk

让我们一步一步来做。 (不确定出了什么问题,代码示例格式不适用于这 3 个示例。)

  1. 获取 IPv4 线路

    wolf@linux:~$ nmcli 设备显示 lo | grep 4.A
    IP4.地址[1]: 127.0.0.1/8
    狼@linux:~$

  2. 使用awk获取IP

    wolf@linux:~$ nmcli 设备显示 lo | awk '/4.A/ {打印 $2}'
    127.0.0.1/8
    狼@linux:~$

  3. 使用 cut 删除 CIDR 符号 (/8)

    wolf@linux:~$ nmcli 设备显示 lo | awk '/4.A/ {print $2}' |剪切-d / -f1
    127.0.0.1
    狼@linux:~$

这就是你的答案。

请注意,使用我刚才演示的工具有很多方法可以做到这一点。

让我们回顾一下我使用的命令。

nmcli device show lo | grep 4.A
nmcli device show lo | awk '/4.A/ {print $2}'
nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1

这 3 个命令的示例输出

命令 1 输出

IP4.ADDRESS[1]:                         127.0.0.1/8

命令 2 输出

127.0.0.1/8

命令 3 输出

127.0.0.1

I don't see any answer with nmcli yet which is a command-line tool for controlling NetworkManager.

So here you go :)

wolf@linux:~$ nmcli device 
DEVICE  TYPE      STATE        CONNECTION 
eth1    ethernet  unavailable  --         
eth0    ethernet  unmanaged    --         
lo      loopback  unmanaged    --         
wolf@linux:~$ 

If you want to get the information from specific network interface (let say lo for this example)

wolf@linux:~$ nmcli device show lo
GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
GENERAL.STATE:                          10 (unmanaged)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --
IP4.ADDRESS[1]:                         127.0.0.1/8
IP4.GATEWAY:                            --
IP4.ROUTE[1]:                           dst = 127.0.0.0/8, nh = 0.0.0.0,>
IP4.ROUTE[2]:                           dst = 127.0.0.1/32, nh = 0.0.0.0>
IP6.ADDRESS[1]:                         ::1/128
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = ::1/128, nh = ::, mt = 256
IP6.ROUTE[2]:                           dst = ::1/128, nh = ::, mt = 0, >
wolf@linux:~$ 

But since you just want to get the IP address, just send the output to grep, cut or awk.

Let's do it step by step. (Not sure what's wrong, the code sample format just didn't work for these 3 example.)

  1. Get the IPv4 line

    wolf@linux:~$ nmcli device show lo | grep 4.A
    IP4.ADDRESS[1]: 127.0.0.1/8
    wolf@linux:~$

  2. Use awk to get the IP

    wolf@linux:~$ nmcli device show lo | awk '/4.A/ {print $2}'
    127.0.0.1/8
    wolf@linux:~$

  3. Use cut to remove the CIDR notation (/8)

    wolf@linux:~$ nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1
    127.0.0.1
    wolf@linux:~$

There your answer.

Please take note that there are tons of ways to do it using the tools that I demonstrated just now.

Let's recap the commands that I used.

nmcli device show lo | grep 4.A
nmcli device show lo | awk '/4.A/ {print $2}'
nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1

Sample output for these 3 commands

Command 1 output

IP4.ADDRESS[1]:                         127.0.0.1/8

Command 2 output

127.0.0.1/8

Command 3 output

127.0.0.1
未蓝澄海的烟 2024-12-28 20:31:01
ip addr|awk '/eth0/ && /inet/ {gsub(/\/[0-9][0-9]/,""); print $2}'

显示你所有的ip

ip addr|awk '/eth0/ && /inet/ {gsub(/\/[0-9][0-9]/,""); print $2}'

shows all your ips

反目相谮 2024-12-28 20:31:01

在 Redhat 64 位上,这解决了我的问题。

ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'

On Redhat 64bit, this solved problem for me.

ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'
多像笑话 2024-12-28 20:31:01
#!/bin/sh
# Tested on Ubuntu 18.04 and Alpine Linux 
# List IPS of following network interfaces:
# virtual host interfaces
# PCI interfaces
# USB interfaces
# ACPI interfaces
# ETH interfaces
for NETWORK_INTERFACE in $(ls /sys/class/net -al | grep -iE "(/eth[0-9]+$|vif|pci|acpi|usb)" | sed -E "s@.* ([^ ]*) ->.*@\1@"); do 
    IPV4_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet addr[: ]+|inet[: ]+)' | sed -E "s@\s*(inet addr[: ]+|inet[: ]+)([^ ]*) .*@\2@")
    IPV6_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet6 addr[: ]+|inet6[: ]+)' | sed -E "s@\s*(inet6 addr[: ]+|inet6[: ]+)([^ ]*) .*@\2@")
    if [ -n "$IPV4_ADDRESSES" ] || [ -n "$IPV6_ADDRESSES" ]; then
        echo "NETWORK INTERFACE=$NETWORK_INTERFACE"
        for IPV4_ADDRESS in $IPV4_ADDRESSES; do 
            echo "IPV4=$IPV4_ADDRESS"
        done
        for IPV6_ADDRESS in $IPV6_ADDRESSES; do 
            echo "IPV6=$IPV6_ADDRESS"
        done
    fi
done
#!/bin/sh
# Tested on Ubuntu 18.04 and Alpine Linux 
# List IPS of following network interfaces:
# virtual host interfaces
# PCI interfaces
# USB interfaces
# ACPI interfaces
# ETH interfaces
for NETWORK_INTERFACE in $(ls /sys/class/net -al | grep -iE "(/eth[0-9]+$|vif|pci|acpi|usb)" | sed -E "s@.* ([^ ]*) ->.*@\1@"); do 
    IPV4_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet addr[: ]+|inet[: ]+)' | sed -E "s@\s*(inet addr[: ]+|inet[: ]+)([^ ]*) .*@\2@")
    IPV6_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet6 addr[: ]+|inet6[: ]+)' | sed -E "s@\s*(inet6 addr[: ]+|inet6[: ]+)([^ ]*) .*@\2@")
    if [ -n "$IPV4_ADDRESSES" ] || [ -n "$IPV6_ADDRESSES" ]; then
        echo "NETWORK INTERFACE=$NETWORK_INTERFACE"
        for IPV4_ADDRESS in $IPV4_ADDRESSES; do 
            echo "IPV4=$IPV4_ADDRESS"
        done
        for IPV6_ADDRESS in $IPV6_ADDRESSES; do 
            echo "IPV6=$IPV6_ADDRESS"
        done
    fi
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文