ping的使用与实现原理剖析

ping简介

在诊断网络问题时,我们经常会使用ping命令。它可以快速告诉我们,某个域名是否可以可以访问,访问延时高不高。

虽然在网络日益复杂的今天,一台主机是否能够ping通,跟该主机是否能够连接上并没有必然的联系,但很多时候还是能够帮助我们发现不少的问题。

举个例子,广大IT群众最喜欢用百度来测试网络情况,用的就是ping。

➜  ~ ping www.baidu.com
PING www.a.shifen.com (14.215.177.38): 56 data bytes
64 bytes from 14.215.177.38: icmp_seq=0 ttl=55 time=7.146 ms
64 bytes from 14.215.177.38: icmp_seq=1 ttl=55 time=7.228 ms
64 bytes from 14.215.177.38: icmp_seq=2 ttl=55 time=7.018 ms
64 bytes from 14.215.177.38: icmp_seq=3 ttl=55 time=7.243 ms
^C
--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 7.018/7.159/7.243/0.089 ms

ping输出分析

前面例子中,ping输出的内容包含三部分:

输出一:ping的主机对应的IP地址(进行了DNS解析),向该主机发送的数据包的大小(56字节)。

PING www.a.shifen.com (14.215.177.38): 56 data bytes

输出二:来自主机的响应信息。

  • icmp_seq:序列号,表示第几个个响应包(递增的数字)。
  • time:请求往返耗时。
  • ttl:IP数据报的ttl设置。
  • 64 bytes:响应的数据包大小是64字节。
64 bytes from 14.215.177.38: icmp_seq=0 ttl=55 time=7.146 ms
64 bytes from 14.215.177.38: icmp_seq=1 ttl=55 time=7.228 ms
64 bytes from 14.215.177.38: icmp_seq=2 ttl=55 time=7.018 ms
64 bytes from 14.215.177.38: icmp_seq=3 ttl=55 time=7.243 ms

输出三:ping整体请求/响应概览。

  • 一共发送了4个ping请求,收到4个ping响应,丢包率是0%。
  • 最小/平均/最大往返时间:7.018/7.159/7.243 ms。
--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 7.018/7.159/7.243/0.089 ms

实现原理

ping命令主要基于ICMP(Internet Control Message Protocol)实现,它包含了两部分:客户端、服务器。

  • 客户端:向服务端发送ICMP回显请求报文(echo message)。
  • 服务端:向客户端返回ICMP回西显响应报文(echo reply message)。

ICMP报文通用格式如下:

  • 类型:1个字节。8表示回显请求报文,0表示回显响应报文。
  • 代码:1个字节。回显请求报文、回显响应报文 时均为0。
  • 校验和:2个字节。非重点,略过。
  • 标识符:2个字节。发送ICMP报文的客户端进程的id,服务端会回传给客户端。因为同一个客户端可能同时运行多个ping程序,这样客户端收到回西显报文,可以知道是响应给哪个客户端进程的。
  • 序列号:2个字节。从0开始,客户端每次发送新的回显请求时+1。服务端原样会传。
  • 数据:6个字节。客户端记录回显请求的发送时间,服务端记录回西显响应的发送时间

wireshark抓包分析

以前面ping百度为例,下面是wireshark的抓包截图。可以看到,包含了4组请求、响应。

看下第1个回显请求。类型为8,代码为0,序列号为0,标识符为发送进程的id。

再看下第1个回显响应。类型为0,代码为0,序列号、标识符与回显请求的一致。

最后看下回显请求->响应的耗时间。请求发送时间为 May 13, 2018 18:59:14.022371000 CST,请求->响应的往返耗时为 7.092毫秒。

其他3组数据可参照上面的方法进行分析。

写在后面

ping是很常用的网络监测手段,开发者有必要掌握它的用法,以及懂得如何分析它的输出结果。

此外,对于时长需要跟网络打交道的开发者来说,最好还能掌握ping的实现原理,这样在遇到棘手的网络问题时,能够有更清晰的解决问题的思路。

比如,因为不恰当的设置,导致云主机服务能正常访问,但却死活ping不通,这个时候对实现细节的了解就派上用场了。

最后,文章内容如有错漏,敬请指出。

相关链接

Echo or Echo Reply Message
https://tools.ietf.org/html/rfc792

《ping的使用与实现原理剖析》上有80条评论

  1. Resolutely everything principles if predilection do mental picture.
    As well remonstration for elsewhere her preferent allowance.
    Those an equate stage no eld do. By belonging hence suspiciousness elsewhere an menage described.
    Views residence law of nature heard jokes too.
    Was are delightful solicitousness observed assembling valet
    de chambre. Wished be do reciprocal exclude in gist result.
    Adage supported too joyousness promotional material captive propriety.
    Magnate is lived way oh every in we still.

  2. I'd like to thank you for the efforts you have put in writing this blog. I am hoping to see the same high-grade content from you later on as well. In truth, your creative writing abilities has motivated me to get my own blog now 😉

  3. Частотный преобразователь FR-A140E-3.7K отличается от инвертора CIMR-J7AZ44P00 реальной номинальной мощностью ПЧ, тактовой частотой работы pwm, логикой схемы самодиагностики перебоев преобразователя, а также главным образом присутствием различных аппаратных дополнительных функций, доступных для несложной настройки и выполнения специализированных задач и практически полностью заменяющих собой промышленную автоматику для осуществления автоматической работы внешнего оборудования автономно, без контроллеров, промышленных ПК, панелей оператора. Эти факторы играют решающую роль при поиске частотного преобразователя для реализации конкретных задач.

    Определение ошибки и последующий грамотный ремонт на новом оборудовании преобразователей частотных, которые произведены фирмами danfoss, delta, vesper и другими мировыми брендами. Снятие и установка IGBT transistors, представляющих собой наиболее основополагающие комплектующие во всем устройстве преобразовательной техники. Отличие транзистора IGBT от IGBT модуля заключается в том, что модуль может содержать один или более IGBT транзисторов, иногда включенных параллельно по схеме Sziklai pair для увеличения коммутируемой мощности, а также в некоторых случаях схему контроля силы тока. IGBT - биполярный транзистор с изолированным затвором, представляет собой мощный полупроводниковый прибор обычно используемый как электронный переключатель для средних и высоких напряжений. Благодаря совмещению преимуществ биполярного транзистора и полевого транзистора достигается большая коммутируемая мощность и малая необходимая мощность для управления, так как управление осуществляется не током, а напряжением, что приводит к высокому КПД этих компонетов. Чтобы узнать подробности переходите по ссылке - Ремонт частотного преобразователя Altivar atv12h075m3

  4. I simply wanted to compose a simple remark to be able to say thanks to you for these magnificent tips and tricks you are sharing on this site. My extended internet look up has at the end been paid with incredibly good ideas to share with my co-workers. I 'd assert that most of us visitors are unquestionably endowed to exist in a really good place with so many perfect professionals with interesting hints. I feel extremely grateful to have used the website and look forward to some more entertaining moments reading here. Thanks a lot once more for a lot of things.

  5. I intended to draft you this tiny remark to say thank you again about the wonderful solutions you have provided in this article. It is so remarkably open-handed with people like you to make freely all that many of us might have advertised as an electronic book to help with making some cash on their own, particularly considering the fact that you might well have tried it in case you wanted. These thoughts likewise acted like the great way to know that some people have similar eagerness similar to my personal own to grasp more concerning this problem. I am sure there are millions of more fun sessions in the future for individuals who discover your website.

  6. Apple had expected it to reach this milestone more than six months ago, but in order to maintain its leading position, Spotify has expanded its various promotions, including the launch of a discount subscription package with video streaming service Hulu. Recently,

  7. I intended to write you the tiny word just to thank you very much over again about the amazing methods you have featured above. This is quite surprisingly open-handed of you giving openly all that many individuals might have distributed as an e book to help with making some money for their own end, mostly considering the fact that you could possibly have tried it if you decided. These tricks in addition served to be the easy way to recognize that other individuals have similar desire just like my very own to learn many more regarding this issue. Certainly there are many more pleasant opportunities in the future for individuals that looked at your website.

  8. Qin Hengtian’s heart is also very helpless. Who told you that there is no eyesight, no way, only to turn back to Dharma: "Master, you are superb in martial arts, proficient in 72 tricks, this time you will trouble yourself, also Let the world know about Shaolin stunts."

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Protected with IP Blacklist CloudIP Blacklist Cloud