Skip to content

Instantly share code, notes, and snippets.

@CIPop
Created August 19, 2022 19:42
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 CIPop/e29729d1c8d6871372f38c8cbcc43f93 to your computer and use it in GitHub Desktop.
Save CIPop/e29729d1c8d6871372f38c8cbcc43f93 to your computer and use it in GitHub Desktop.
Dual-mode IPv4/IPv6 socket client for Linux
// Based on the dual-mode IPv4/IPv6 example in "The Linux Programming Interface", M. Kerrisk, 2010
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
#define PORT_NUM "443"
static void print_error(char* extraMessage)
{
printf("ERROR: %s: %d - %s\n", extraMessage, errno, strerror(errno));
}
static void exit_error(char* extraMessage)
{
print_error(extraMessage);
abort();
}
int main(int argc, char **argv)
{
int ret;
struct addrinfo hints = {0};
hints.ai_family = AF_UNSPEC; // Not specified: IPv4 or IPv6.
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
if (argc < 2)
{
printf("Example usage:\n\tclient <https_host_name>\n");
return 1;
}
struct addrinfo *name_resolution_result;
if (0 != getaddrinfo(argv[1], PORT_NUM, &hints, &name_resolution_result))
{
exit_error("getaddrinfo failed");
}
struct addrinfo *rec;
for (rec = name_resolution_result; rec != NULL; rec = rec->ai_next)
{
char host_name[255];
if (0 != getnameinfo(rec->ai_addr, rec->ai_addrlen, host_name, sizeof(host_name), NULL, 0, NI_NUMERICHOST))
{
print_error("getnameinfo failed");
continue;
}
printf("Server Address: \t IPv%d: \t %s\n", rec->ai_family == AF_INET6 ? 6 : 4, host_name);
int socket_fd = socket(rec->ai_family, rec->ai_socktype, rec->ai_protocol);
if (socket_fd == -1)
{
print_error("socket failed");
continue;
}
if (0 != connect(socket_fd, rec->ai_addr, rec->ai_addrlen))
{
print_error("connect failed");
}
else
{
printf("\tCONNECTED!\n");
}
close(socket_fd);
}
freeaddrinfo(name_resolution_result);
return 0;
}
@CIPop
Copy link
Author

CIPop commented Aug 19, 2022

gcc client_ipv4_ipv6.c && ./a.out www.bing.com
Server Address:          IPv6:   2620:1ec:cxx::x00
        CONNECTED!
Server Address:          IPv4:   13.1xx.xx.xx0
        CONNECTED!
Server Address:          IPv4:   204.7x.x1x.xx0
        CONNECTED!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment