open-card-table/oct_networking.c

78 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include "oct_networking.h"
struct {
int needs_recv;
int needs_send;
char recv_buffer[BUFFER_SIZE];
char send_buffer[BUFFER_SIZE];
int sock_fd;
} oct_network_client;
struct {
int needs_recv;
int needs_send;
char recv_buffer[BUFFER_SIZE];
char send_buffer[BUFFER_SIZE];
int sfd;
} oct_network_server;
int oct_network_server_init(char* port) {
oct_network_server.needs_recv = 0;
oct_network_server.needs_send = 0;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // ipv4 or ipv6
hints.ai_socktype = SOCK_DGRAM; // datagram
hints.ai_flags = AI_PASSIVE; // any IP address
hints.ai_protocol = 0; // any protocol
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
struct addrinfo* result;
int s = getaddrinfo(NULL, port, &hints, &result);
if (s != 0) {
//fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return 0;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */
struct addrinfo *rp;
for (rp = result; rp != NULL; rp = rp->ai_next) {
oct_network_server.sfd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (oct_network_server.sfd == -1)
continue;
if (bind(oct_network_server.sfd, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
close(oct_network_server.sfd);
}
freeaddrinfo(result);
if (!rp) {
return 0;
}
return 1;
}