60 lines
1.8 KiB
C
60 lines
1.8 KiB
C
// get sockaddr, IPv4 or IPv6:
|
|
static void *get_in_addr(struct sockaddr *sa) {
|
|
if (sa->sa_family == AF_INET) {
|
|
return &(((struct sockaddr_in*)sa)->sin_addr);
|
|
}
|
|
return &(((struct sockaddr_in6*)sa)->sin6_addr);
|
|
}
|
|
|
|
/*
|
|
DEBUG TOOL
|
|
print a packet
|
|
*/
|
|
static int p_printf_packet(p3_msg_t *packet) {
|
|
return printf("Packet header (%lu): {magic_number: %X, packet_id: %x, TTL: %i,"
|
|
" destination_host: %x, destination_plugin: %x, body_length: %u}\n",
|
|
sizeof(*packet), packet->magic_number.value, packet->packet_id,
|
|
packet->TTL, packet->destination_host, packet->destination_plugin,
|
|
packet->body_length) +
|
|
printf("Packet body: %s\n", (char *)packet + sizeof(*packet));
|
|
}
|
|
|
|
static int p_stop_server() {
|
|
if (server_p != -1)
|
|
close(server_p);
|
|
server_p = -1;
|
|
return 0;
|
|
}
|
|
|
|
/* Start the server on the specified port. The file descriptor of the server is stored in server_p */
|
|
static int p_start_server(char *port) {
|
|
p_stop_server(); // STOP THE SERVER IF ALREADY STARTED
|
|
|
|
int sockfd;
|
|
struct addrinfo hints, *servinfo;
|
|
int rv;
|
|
|
|
memset(&hints, 0, sizeof hints);
|
|
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
|
|
hints.ai_socktype = SOCK_DGRAM;
|
|
hints.ai_flags = AI_PASSIVE; // use my IP
|
|
if ((rv = getaddrinfo(NULL, port, &hints, &servinfo)) != 0) {
|
|
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
|
|
return ERR_SYSCALL;
|
|
}
|
|
// loop through all the results and bind to the first we can
|
|
if ((sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) {
|
|
perror("socket");
|
|
return ERR_SYSCALL;
|
|
}
|
|
if (bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1) {
|
|
close(sockfd);
|
|
perror("bind");
|
|
return ERR_SYSCALL;
|
|
}
|
|
|
|
freeaddrinfo(servinfo);
|
|
server_p = sockfd;
|
|
return 0;
|
|
}
|