eventstore-client-c/socket.c

61 lines
1.3 KiB
C
Raw Normal View History

2018-03-19 05:44:23 +00:00
//
// Created by nicol on 2018-03-18.
//
#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);
}
int socket_send(socket_t s, char* data, int len) {
return send(s->s, data, len, 0);
}
int socket_recv(socket_t s, char* buf, int len) {
return recv(s->s, buf, len, 0);
}
int socket_error() {
return WSAGetLastError();
}
#endif