76 lines
1.9 KiB
C
76 lines
1.9 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
#include <sys/socket.h>
|
|
#include <sys/types.h> // BSD compatible
|
|
#include <arpa/inet.h>
|
|
#include <unistd.h>
|
|
|
|
#include <errno.h>
|
|
#include <netdb.h>
|
|
|
|
#include "network.h"
|
|
|
|
const int DGRAM_MSG_START = 0;
|
|
const int DGRAM_PAYLOAD_START = DGRAM_MSG_START + DGRAM_MSG_LENGTH + DGRAM_NULL_LENGTH;
|
|
|
|
int sendToXPlane(int sock, char *msg, char *payload) {
|
|
char bytesToSend[SEND_BUFFER];
|
|
memset(bytesToSend, 0, SEND_BUFFER);
|
|
|
|
// msg is always 4 bytes long
|
|
if (strlen(msg) != DGRAM_MSG_LENGTH) {
|
|
return -10;
|
|
}
|
|
|
|
// payload shouldn't exceed buffer
|
|
if (strlen(payload) > (SEND_BUFFER - DGRAM_MSG_LENGTH - DGRAM_NULL_LENGTH)) {
|
|
return -11;
|
|
}
|
|
|
|
strcpy(&bytesToSend[DGRAM_MSG_START], msg);
|
|
strcpy(&bytesToSend[DGRAM_PAYLOAD_START], payload);
|
|
|
|
int numBytesSend = send(sock, bytesToSend, DGRAM_MSG_LENGTH + DGRAM_NULL_LENGTH + strlen(payload), 0);
|
|
if (numBytesSend >= 0) {
|
|
return numBytesSend;
|
|
} else {
|
|
fprintf(stderr, "Failed to send message (%d): %s", errno, strerror(errno));
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
int connectXPlane(char *addr, int port) {
|
|
int xPlaneSocket;
|
|
struct sockaddr_in6 xPlaneAddress;
|
|
|
|
int err;
|
|
|
|
// create socket
|
|
xPlaneSocket = socket(AF_INET6, SOCK_DGRAM, 0);
|
|
if (xPlaneSocket == -1) {
|
|
fprintf(stderr, "Error creating socket (%d): %s\n", errno, strerror(errno));
|
|
return -1;
|
|
}
|
|
|
|
// prepare address struct
|
|
xPlaneAddress.sin6_family = AF_INET6;
|
|
xPlaneAddress.sin6_port = htons(PORT);
|
|
inet_pton(AF_INET6, SERVER, &xPlaneAddress.sin6_addr.s6_addr);
|
|
|
|
// connect to xPlane
|
|
err = connect(xPlaneSocket, (struct sockaddr *)&xPlaneAddress, sizeof(xPlaneAddress));
|
|
if (err) {
|
|
fprintf(stderr, "Error connecting %s:%d (%d): %s\n", addr, port, err, gai_strerror(err));
|
|
return -1;
|
|
}
|
|
|
|
return xPlaneSocket;
|
|
}
|
|
|
|
int disconnectXPlane(int sock) {
|
|
// bye bye (and no, I don't care about error anymore; I'll exit anyway?!)
|
|
close(sock);
|
|
}
|