Skip to content

Instantly share code, notes, and snippets.

@shimarin
Last active February 11, 2021 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimarin/f1486dc2e26093aa88c9794b1d821fbe to your computer and use it in GitHub Desktop.
Save shimarin/f1486dc2e26093aa88c9794b1d821fbe to your computer and use it in GitHub Desktop.
/**
* ICMPv6 echo request (ping6) test
*/
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/icmp6.h>
#include <iostream>
int main()
{
struct sockaddr_in6 whereto;
whereto.sin6_family = AF_INET6;
whereto.sin6_port = htons(0);
inet_pton(AF_INET6, "2001:4860:4860::8888"/*Google Public DNS*/, &whereto.sin6_addr);
auto sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); // You need to be root to do this
// https://tools.ietf.org/html/rfc4443
unsigned char buf[sizeof(struct icmp6_hdr) + 8];
auto icmph = (struct icmp6_hdr *)buf;
icmph->icmp6_type = ICMP6_ECHO_REQUEST;
icmph->icmp6_code = 0;
icmph->icmp6_cksum = 0;
icmph->icmp6_seq= 1;
icmph->icmp6_id= 0;
strcpy((char*)buf + sizeof(struct icmp6_hdr), "RUTHERE");
auto n = sendto(sock, buf, sizeof(buf), 0/*flags*/, (struct sockaddr *)&whereto, sizeof(struct sockaddr_in6));
std::cout << (int)n << " bytes sent" << std::endl;
n = recvfrom(sock, buf, sizeof(buf), 0, NULL, NULL); // blocks until reply packet arrives(possibly forever)
std::cout << (int)n << " bytes received. code=" << (int)buf[0] << std::endl;
close(sock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment