81 lines
2.1 KiB
C
81 lines
2.1 KiB
C
#include "net.h"
|
|
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
#include <arpa/inet.h>
|
|
|
|
int net_client_init(net_t *const n, const int af_family, const char *const raddr, const int rport) {
|
|
if ((n->fd = socket(af_family, SOCK_DGRAM, 0)) == -1 )
|
|
return -1;
|
|
|
|
memset(&n->inaddr, 0, sizeof(n->inaddr));
|
|
n->inaddr_len = sizeof(n->inaddr);
|
|
|
|
memset(&n->raddr, 0, sizeof(n->raddr));
|
|
n->raddr.sin_family = af_family;
|
|
n->raddr.sin_addr.s_addr = inet_addr(raddr);
|
|
n->raddr.sin_port = htons(rport);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int net_server_init(net_t *const n, const int af_family, const char *const laddr, const int lport) {
|
|
if ((n->fd = socket(af_family, SOCK_DGRAM, 0)) == -1 )
|
|
return -1;
|
|
|
|
memset(&n->inaddr, 0, sizeof(n->inaddr));
|
|
n->inaddr_len = sizeof(n->inaddr);
|
|
|
|
memset(&n->laddr, 0, sizeof(n->laddr));
|
|
n->laddr.sin_family = af_family;
|
|
n->laddr.sin_addr.s_addr = inet_addr(laddr);
|
|
n->laddr.sin_port = htons(lport);
|
|
|
|
memset(&n->raddr, 0, sizeof(n->raddr));
|
|
n->raddr_len = sizeof(n->raddr);
|
|
|
|
if (bind(n->fd, (struct sockaddr *)&n->laddr, sizeof(n->laddr)) == -1)
|
|
return -1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
void net_destroy(net_t *n) {
|
|
if (n->fd > 0) {
|
|
close(n->fd);
|
|
n->fd = -1;
|
|
}
|
|
|
|
memset(&n->raddr, 0, sizeof(n->raddr));
|
|
n->raddr_len = sizeof(n->raddr);
|
|
memset(&n->laddr, 0, sizeof(n->laddr));
|
|
|
|
memset(&n->buffer, 0, NET_BUFLEN);
|
|
}
|
|
|
|
int net_sendto(net_t *const n, const char *const buf, const int buf_len) {
|
|
if (n->fd == -1)
|
|
return -1;
|
|
|
|
if (sendto(n->fd, buf, buf_len, 0, (struct sockaddr *)&n->raddr, sizeof(n->raddr)) == -1)
|
|
return -1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int net_recvfrom(net_t *const n) {
|
|
if (n->fd == -1 || n->raddr.sin_addr.s_addr == 0)
|
|
return -1;
|
|
|
|
if ((recvfrom(n->fd, n->buffer, NET_BUFLEN, 0, (struct sockaddr *)&n->inaddr, &n->inaddr_len)) == -1)
|
|
return -1;
|
|
|
|
if (n->raddr.sin_addr.s_addr != n->inaddr.sin_addr.s_addr) {
|
|
/* Incoming packet doesn't originate from the one we are talking to. Drop it. */
|
|
return 0;
|
|
}
|
|
|
|
return 0;
|
|
}
|