96 lines
2.5 KiB
C
96 lines
2.5 KiB
C
#include "tcp.h"
|
|
#include <BaseTsd.h>
|
|
#include <WS2tcpip.h>
|
|
#include <WinSock2.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
struct TcpServer {
|
|
int server_socket;
|
|
struct sockaddr_in server_address;
|
|
};
|
|
|
|
struct TcpConnection {
|
|
int client_socket;
|
|
struct sockaddr_in client_address;
|
|
};
|
|
|
|
void tcp_global_initialize_sockets(void)
|
|
{
|
|
WSADATA data;
|
|
WSAStartup(0x0202, &data);
|
|
}
|
|
|
|
TcpServer* tcp_server_create(const char* ip, uint16_t port)
|
|
{
|
|
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (server_socket < 0) {
|
|
printf("error: tcp: could not open socket\n");
|
|
return NULL;
|
|
}
|
|
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int)) < 0) {
|
|
printf("warning: tcp: could not setsockopt SO_REUSEADDR\n");
|
|
}
|
|
struct sockaddr_in server_address;
|
|
server_address.sin_addr.s_addr = inet_addr(ip);
|
|
server_address.sin_family = AF_INET;
|
|
server_address.sin_port = htons(port);
|
|
if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
|
|
printf("error: tcp: could not bind socket\n");
|
|
return NULL;
|
|
}
|
|
if (listen(server_socket, SOMAXCONN) < 0) {
|
|
printf("error: tcp: could not listen on server\n");
|
|
return NULL;
|
|
}
|
|
|
|
TcpServer* self = malloc(sizeof(TcpServer));
|
|
*self = (TcpServer) {
|
|
.server_socket = server_socket,
|
|
.server_address = server_address,
|
|
};
|
|
return self;
|
|
}
|
|
|
|
void tcp_server_destroy(TcpServer* server)
|
|
{
|
|
closesocket(server->server_socket);
|
|
free(server);
|
|
}
|
|
|
|
TcpConnection* tcp_server_accept(TcpServer* server)
|
|
{
|
|
struct sockaddr_in client_address;
|
|
socklen_t client_size;
|
|
int client_socket
|
|
= accept(server->server_socket, (struct sockaddr*)&client_address, &client_size);
|
|
if (client_socket < 0) {
|
|
printf("error: tcp: could not accept connection\n");
|
|
return NULL;
|
|
}
|
|
|
|
TcpConnection* connection = malloc(sizeof(TcpConnection));
|
|
*connection = (TcpConnection) {
|
|
.client_socket = client_socket,
|
|
.client_address = client_address,
|
|
};
|
|
return connection;
|
|
}
|
|
|
|
void tcp_connection_destroy(TcpConnection* connection)
|
|
{
|
|
closesocket(connection->client_socket);
|
|
free(connection);
|
|
}
|
|
|
|
ssize_t tcp_recieve(TcpConnection* connection, uint8_t* data, size_t amount)
|
|
{
|
|
return recv(connection->client_socket, data, amount, 0);
|
|
}
|
|
|
|
ssize_t tcp_send(TcpConnection* connection, uint8_t* data, size_t amount)
|
|
{
|
|
return send(connection->client_socket, data, amount, 0);
|
|
}
|