Skip to content

Instantly share code, notes, and snippets.

@E-gy
Last active December 21, 2021 00:55
Show Gist options
  • Select an option

  • Save E-gy/a0743664e5c491e2d46f0fba3cdff263 to your computer and use it in GitHub Desktop.

Select an option

Save E-gy/a0743664e5c491e2d46f0fba3cdff263 to your computer and use it in GitHub Desktop.
Linux C ICMP getaddrinfo & bind test
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char* args[]){
int sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP);
if(sock < 0){
perror("`socket` failed");
return 1;
}
if(argc > 1){
struct addrinfo hints = {0};
hints.ai_family = AF_INET;
struct addrinfo* addrs;
int gai_ec = getaddrinfo(args[1], NULL, &hints, &addrs);
if(gai_ec != 0){
printf("`getaddrinfo` failed: %s\n", gai_strerror(gai_ec));
close(sock);
return 1;
}
struct addrinfo* candidate = addrs;
for(; candidate != NULL; candidate = candidate->ai_next){
if(bind(sock, candidate->ai_addr, candidate->ai_addrlen) == 0) break;
else perror("`bind` failed with");
}
if(candidate == NULL){
printf("`bind`s failed\n");
freeaddrinfo(addrs);
close(sock);
return 1;
}
freeaddrinfo(addrs);
printf("bound to %s - ", args[1]);
} else {
struct sockaddr_in addr = {0};
addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sock, &addr, sizeof(addr)) < 0){
perror("`bind` failed");
close(sock);
return 1;
}
printf("bound to all interfaces - ", args[1]);
}
printf("okay!\n");
close(sock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment