目录

1. 为什么要使用指定网卡ping操作

2. 使用指定网卡ping操作

3. 总结

1、 为什么要使用指定网卡ping操作

现在很多服务器都拥有双网卡甚至多网卡,有些是为了保持高可用,有些是网络隔离(内网与外网或者不同网络)

很多学者在模拟企业级环境时也为一台虚拟机配置了双网卡,一块NAT模式,一块LAN区段模式,如果使用简单的ping ip形式的命令得到ping通的结果,只能证明两个虚拟机可以ping通,那究竟是使用了哪块网卡去ping另一个虚拟机?

2、实现使用指定网卡进行ping操作

(1) 查ping的帮助

遇到问题首先就想到查看命令帮助,获取到的帮助如下:

1 # ping --help

2 ping: invalid option -- '-'

3 Usage: ping [-aAbBdDfhLnOqrRUvV64] [-c count] [-i interval] [-I interface]

4 [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]

5 [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]

6 [-w deadline] [-W timeout] [hop1 ...] destination

7 Usage: ping -6 [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]

8 [-l preload] [-m mark] [-M pmtudisc_option]

9 [-N nodeinfo_option] [-p pattern] [-Q tclass] [-s packetsize]

10 [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline]

11 [-W timeout] destination

一眼就看到了这个 -I 接口 这个选项(也就这个沾点边),其他完全没有看出任何可以指定网卡设备的可能,接下来查看下man帮助,搜索 -I 这个选项查看详细解释。

1 # man ping

2 -I interface

3 interface is either an address, or an interface name. If interface is an

4 address, it sets source address to specified interface address. If interface in

5 an interface name, it sets source interface to specified interface. For IPv6,

6 when doing ping to a link-local scope address, link specification (by the

7 '%'-notation in destination, or by this option) is required.

本人英文不好,百度翻译了一下,大概意思为:接口可以是地址,也可以是接口名。如果接口是4地址,将源地址设置为指定的接口地址。

也就是说, -I 接口 这个接口可以是网卡设备名,也可以是网卡设备的IP地址。接下来进行试验

(2) 使用 -I 选项实现指定网卡进行ping操作

我的linux虚拟机(主机A)有两张网卡,一张是NAT(192.168.187.10),另一张是LAN区段(172.16.0.10)

第二台虚拟机(主机B),一张NAT(192.168.187.11),另一张是LAN区段(172.16.0.11)

正常情况下 主机A ping 主机B 是可以ping通的,但是不知道使用的是那张网卡:

1 # ping 192.168.187.11

2 PING 192.168.187.11 (192.168.187.11) 56(84) bytes of data.

3 64 bytes from 192.168.187.11: icmp_seq=1 ttl=64 time=1.21 ms

4 64 bytes from 192.168.187.11: icmp_seq=2 ttl=64 time=0.686 ms

使用IP地址指定主机A的NAT网卡ping主机B的LAN区段网卡(理论不能ping通):

1 # ping -I 192.168.187.10 172.16.0.11

2 PING 172.16.0.11 (172.16.0.11) from 192.168.187.10 : 56(84) bytes of data.

3 From 192.168.187.10 icmp_seq=1 Destination Host Unreachable

实际确实ping不通,而且显示 PING 172.16.0.11 (172.16.0.11) from 192.168.187.10 证明ping操作是来自IP地址为192.168.187.10这块网卡的,实验成功

另一种方式,使用主机A的NAT网卡名ping主机B的NAT网卡(理论可以ping通):

1 # ping -I ens33 192.168.187.11

2 PING 192.168.187.11 (192.168.187.11) from 192.168.187.10 ens33: 56(84) bytes of data.

3 64 bytes from 192.168.187.11: icmp_seq=1 ttl=64 time=18.1 ms

4 64 bytes from 192.168.187.11: icmp_seq=2 ttl=64 time=4.11 ms

实验成功,显示的也是 ping 192.168.187.11 来自 192.168.187.10 ens33网卡。

3、总结

ping命令可以使用指定网卡进行ping操作

用法是:

1 # ping -I 本机指定网卡名或网卡的IP地址 目标地址

个人公众号(linuxjsz)

个人博客:http://henkeyi1101.xyz

专注IT技术、知识分享,面试资源共享、讲解

只做全网最比心的公众号,欢迎你的关注!