Created
August 19, 2022 19:42
-
-
Save CIPop/e29729d1c8d6871372f38c8cbcc43f93 to your computer and use it in GitHub Desktop.
Dual-mode IPv4/IPv6 socket client for Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Author
CIPop
commented
Aug 19, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment