How to ping using C sockets

会有一股神秘感。 提交于 2019-12-01 03:45:36

If you don't have to implement the ping from scratch and you want only Windows solution, I'd second Anton's suggestion for IcmpSendEcho. If you have to implement ping, look at how POCO ICMP package is implemented. It is portable code and it runs fine on Windows.

In regards to the specific questions, here are the answers:

what header files should I include

#include <winsock2.h>

how do I create a ping packet

See ICMPv4PacketImpl::initPacket() for an example of IPv4 packet.

am I using the correct checksum generator function

Not for windows. See ICMPPacketImpl::checksum() for an example of checksum function.

should a ping be directed to port 80

No. There's no such thing as port when it comes to ICMP. See Does ICMP use a specific port?

should the socket I use be RAW or DGRAM

It should be RAW.

It looks like you want a real solution, not just reimplementing PING for the sake of it.

I recommend using IP helper (ICMP.dll on pre-WinXP systems), specifically, IcmpSendEcho (or its enhanced versions, IcmpSendEcho2, IcmpSendEcho2Ex, for asynchronous operations).

There is a complete example of "pinging" a host on MSDN. It may be a good starting point.

Update: for GCC (mingw), link with -liphlpapi.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!