common: make a common interface for creating a server socket

This commit is contained in:
Tyler Wilding
2022-04-26 21:32:46 -04:00
parent d41fe7e6ad
commit fe36687366
19 changed files with 416 additions and 325 deletions
+28 -5
View File
@@ -16,6 +16,8 @@
#include <stdio.h>
#include <string.h>
#include "third-party/fmt/core.h"
int open_socket(int af, int type, int protocol) {
#ifdef __linux
return socket(af, type, protocol);
@@ -32,6 +34,20 @@ int open_socket(int af, int type, int protocol) {
#endif
}
int accept_socket(int socket, sockaddr* addr, int* addrLen) {
#ifdef _WIN32
WSADATA wsaData = {0};
int iResult = 0;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
#endif
return accept(socket, addr, addrLen);
}
void close_socket(int sock) {
if (sock < 0) {
return;
@@ -77,19 +93,26 @@ int set_socket_timeout(int socket, long microSeconds) {
}
int write_to_socket(int socket, const char* buf, int len) {
int bytes_wrote;
#ifdef __linux
return write(socket, buf, len);
bytes_wrote = write(socket, buf, len);
#elif _WIN32
return send(socket, buf, len, 0);
bytes_wrote = send(socket, buf, len, 0);
#endif
if (bytes_wrote < 0) {
fmt::print(stderr, "[XSocket:{}] Error writing to socket\n", socket);
}
return bytes_wrote;
}
int read_from_socket(int socket, char* buf, int len) {
int bytes_read;
#ifdef __linux
return read(socket, buf, len);
bytes_read = read(socket, buf, len);
#elif _WIN32
return recv(socket, buf, len, 0);
bytes_read = recv(socket, buf, len, 0);
#endif
return bytes_read;
}
bool socket_timed_out() {
@@ -99,4 +122,4 @@ bool socket_timed_out() {
auto err = WSAGetLastError();
return err == WSAETIMEDOUT;
#endif
}
}