How to ping using C sockets

后端 未结 2 563
别那么骄傲
别那么骄傲 2021-01-12 04:14
  • Compiler: Code::Blocks(GNU GCC)
  • Platform: Windows(x86)
  • Includes: winsock.h winsock2.h (ws2_32 is linked as well)

I am currently tryin

相关标签:
2条回答
  • 2021-01-12 04:45

    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.

    0 讨论(0)
  • 2021-01-12 04:47

    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.

    0 讨论(0)
提交回复
热议问题