ipv6 + misc

This commit is contained in:
2025-05-03 11:22:38 +02:00
parent 3b73f82938
commit 1e8fcc4879
3 changed files with 157 additions and 76 deletions
+38 -9
View File
@@ -1,5 +1,10 @@
#include "../common/defines.h"
#include <arpa/inet.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
@@ -54,23 +59,47 @@ int main(int argc, char *argv[]) {
error("Error setting cipher list");
}
// Create a TCP socket
// Socket creation will be handled in the connection loop
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("Socket creation failed");
// Set up server address
struct sockaddr_in serv_addr;
struct sockaddr_storage serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
if (inet_pton(AF_INET, argv[1], &serv_addr.sin_addr) <= 0)
error("Invalid address/address not supported");
// Connect to server
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
struct addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Enable IPv4/IPv6 dual support
hints.ai_socktype = SOCK_STREAM;
// Resolve hostname and port together
int status = getaddrinfo(argv[1], argv[2], &hints, &res);
if (status != 0) {
std::cerr << "Resolution failed: " << gai_strerror(status) << "\n";
std::exit(EINVAL);
}
// Try all addresses until successful connection
struct addrinfo *rp;
for (rp = res; rp != NULL; rp = rp->ai_next) {
sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1)
continue;
if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) == 0)
break; // Success
close(sockfd);
sockfd = -1;
}
freeaddrinfo(res); // Free after connection attempts
if (sockfd == -1) {
std::cerr << "Failed to connect to all resolved addresses\n";
freeaddrinfo(res);
error("Connection failed");
}
printf("Connected to %s:%s\n", argv[1], argv[2]);
// Create an SSL object