2018-03-19 22:48:55 -07:00

133 lines
2.8 KiB
C

//
// Created by nicol on 2018-03-18.
//
#include <stdlib.h>
#include <unistd.h>
#include "socket.h"
#ifdef _WIN32
#include <ws2tcpip.h>
struct st_socket {
SOCKET s;
int af;
int type;
int proto;
};
socket_t socket_create(int type) {
if (type == SOCKET_TYPE_TCP) {
socket_t s = malloc(sizeof(struct st_socket));
s->af = AF_INET;
s->type = SOCK_STREAM;
s->proto = IPPROTO_TCP;
s->s = socket(s->af, s->type, s->proto);
if (s->s == INVALID_SOCKET) {
free(s);
return NULL;
}
return s;
}
return NULL;
}
void socket_close(socket_t s) {
closesocket(s->s);
}
int socket_connect(socket_t s, char* addr, unsigned short port) {
char port_s[6];
ADDRINFO hints;
memset(&hints, 0, sizeof(ADDRINFO));
hints.ai_family = s->af;
hints.ai_socktype = s->type;
hints.ai_protocol = s->proto;
ADDRINFO* result;
if (getaddrinfo(addr, itoa(port, port_s, 10), &hints, &result) != 0) {
return -1;
}
return connect(s->s, result->ai_addr, (int)result->ai_addrlen);
}
ssize_t socket_send(socket_t s, char* data, size_t len) {
return send(s->s, data, (int)len, 0);
}
ssize_t socket_recv(socket_t s, char* buf, size_t len) {
return recv(s->s, buf, (int)len, 0);
}
int socket_readable(socket_t s) {
fd_set readable;
FD_SET(s->s, &readable);
struct timeval timeout = {0, 0};
return select(0, &readable, 0, 0, &timeout);
}
int socket_error() {
return WSAGetLastError();
}
#endif
#ifdef __linux__
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
struct st_socket {
int s;
int af;
int type;
int proto;
};
socket_t socket_create(int type) {
if (type == SOCKET_TYPE_TCP) {
socket_t s = malloc(sizeof(struct st_socket));
s->af = AF_INET;
s->type = SOCK_STREAM;
s->proto = IPPROTO_TCP;
s->s = socket(s->af, s->type, s->proto);
if (s->s == -1) {
free(s);
return NULL;
}
return s;
}
return NULL;
}
void socket_close(socket_t s) {
close(s->s);
}
int socket_connect(socket_t s, char* addr, unsigned short port) {
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = s->af;
hints.ai_socktype = s->type;
hints.ai_protocol = s->proto;
struct addrinfo* result;
char port_s[6];
snprintf(port_s, 6, "%d", port);
if (getaddrinfo(addr, port_s, &hints, &result) != 0) {
return -1;
}
return connect(s->s, result->ai_addr, (int)result->ai_addrlen);
}
ssize_t socket_send(socket_t s, char* data, size_t len) {
return send(s->s, data, len, 0);
}
ssize_t socket_recv(socket_t s, char* buf, size_t len) {
return recv(s->s, buf, len, 0);
}
int socket_error() {
return errno;
}
#endif