voice-chat/src/main.c

90 lines
2.0 KiB
C
Raw Normal View History

2026-01-16 15:31:50 -05:00
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl3.h>
#include <netdb.h>
#include <stdarg.h>
#include <stdio.h>
2026-01-16 15:31:50 -05:00
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "log.h"
void
die(const char *errstr, ...) {
va_list ap;
va_start(ap, errstr);
vfprintf(stderr, errstr, ap);
va_end(ap);
exit(1);
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
// Client connection
typedef struct {
2026-01-16 15:31:50 -05:00
int fd;
} cconnection_t;
2026-01-16 15:31:50 -05:00
void*
get_in_addr(struct sockaddr *addr) {
if (addr->sa_family == AF_INET) {
return &((struct sockaddr_in*)addr)->sin_addr;
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
return &((struct sockaddr_in6*)addr)->sin6_addr;
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
// Returns error or nullptr
char*
connect_server(char *hostname, char *port, cconnection_t *connection) {
int rv;
struct addrinfo hints, *res, *p;
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
if ((rv = getaddrinfo(hostname, port, &hints, &res)) != 0) {
die("error getting address info: %s\n", gai_strerror(rv));
2026-01-14 22:49:49 -05:00
}
2026-01-16 15:31:50 -05:00
int fd;
char ip_str[INET6_ADDRSTRLEN];
for (p = res; p != nullptr; p = p->ai_next) {
if ((fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
close(fd);
continue;
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
inet_ntop(p->ai_family, get_in_addr(p->ai_addr), ip_str, sizeof(ip_str));
if (connect(fd, p->ai_addr, p->ai_addrlen) != 0) {
log_warn("Connection to %s:%s unsuccessful. %s", ip_str, port, strerror(errno));
continue;
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
log_info("Connection to %s successful", ip_str);
break;
2026-01-14 22:49:49 -05:00
}
2026-01-16 15:31:50 -05:00
if (p == nullptr) {
ssize_t err_size = 512;
char *err = malloc(512);
snprintf(err, err_size, "Failed to connect to %s:%s", hostname, port);
return err;
2026-01-14 22:49:49 -05:00
}
2026-01-16 15:31:50 -05:00
freeaddrinfo(res);
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
return nullptr;
}
2026-01-14 22:49:49 -05:00
2026-01-16 15:31:50 -05:00
int
main() {
if(nullptr == NULL) return 1;
2026-01-14 22:33:58 -05:00
return 0;
}