summaryrefslogtreecommitdiffhomepage
path: root/src
diff options
context:
space:
mode:
authorRay <[email protected]>2020-02-18 18:15:22 +0100
committerRay <[email protected]>2020-02-18 18:15:22 +0100
commit6d1cdf25a7d01bef2558b48f4c497724afe40139 (patch)
tree26d035d987bf88988851568269901498910f6bbb /src
parent51db3b589df2d54aaa3880c36df5c8c082d214e4 (diff)
downloadraylib-6d1cdf25a7d01bef2558b48f4c497724afe40139.tar.gz
raylib-6d1cdf25a7d01bef2558b48f4c497724afe40139.zip
[rnet] Review module formating
Align formating with other raylib modules coding style.
Diffstat (limited to 'src')
-rw-r--r--src/rnet.c.review1009
-rw-r--r--src/rnet.h147
2 files changed, 496 insertions, 660 deletions
diff --git a/src/rnet.c.review b/src/rnet.c.review
index 46654ded..dcec045c 100644
--- a/src/rnet.c.review
+++ b/src/rnet.c.review
@@ -5,17 +5,13 @@
* FEATURES:
* - Provides a simple and (hopefully) easy to use wrapper around the Berkeley socket API
*
-* DEPENDENCIES:
-* raylib.h - TraceLog
-* rnet.h - platform-specific network includes
-*
* CONTRIBUTORS:
* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version
*
*
* LICENSE: zlib/libpng
*
-* Copyright (c) 2019 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5)
+* Copyright (c) 2019-2020 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5)
*
* This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software.
@@ -40,18 +36,25 @@
#include "rnet.h"
-#include "raylib.h"
-
#include <assert.h> // Required for: assert()
#include <stdio.h> // Required for: FILE, fopen(), fclose(), fread()
#include <stdlib.h> // Required for: malloc(), free()
#include <string.h> // Required for: strcmp(), strncmp()
-//----------------------------------------------------------------------------------
-// Module defines
-//----------------------------------------------------------------------------------
+#define NET_DEBUG_ENABLED 1
+
+#if defined(SUPPORT_TRACELOG)
+ #define TRACELOG(level, ...) TraceLog(level, __VA_ARGS__)
-#define NET_DEBUG_ENABLED (1)
+ #if defined(SUPPORT_TRACELOG_DEBUG)
+ #define TRACELOGD(...) TraceLog(LOG_DEBUG, __VA_ARGS__)
+ #else
+ #define TRACELOGD(...) (void)0
+ #endif
+#else
+ #define TRACELOG(level, ...) (void)0
+ #define TRACELOGD(...) (void)0
+#endif
//----------------------------------------------------------------------------------
// Types and Structures Definition
@@ -82,12 +85,9 @@ typedef struct _AddressInformation
struct addrinfo addr;
} _AddressInformation;
-
-
//----------------------------------------------------------------------------------
-// Global module forward declarations
+// Local module Functions Declarations
//----------------------------------------------------------------------------------
-
static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol);
static const char *SocketAddressToString(struct sockaddr_storage *sockaddr);
static bool IsIPv4Address(const char *ip);
@@ -108,64 +108,50 @@ static bool SocketSetOptions(SocketConfig *config, Socket *sock);
static void SocketSetHints(SocketConfig *config, struct addrinfo *hints);
//----------------------------------------------------------------------------------
-// Global module implementation
+// Local module Functions Definition
//----------------------------------------------------------------------------------
-
// Print socket information
static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol)
{
switch (family)
{
- case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified");
- }
- break;
+ case AF_UNSPEC: TRACELOG(LOG_DEBUG, "\tFamily: Unspecified"); break;
case AF_INET:
{
- TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)");
- TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr));
- }
- break;
+ TRACELOG(LOG_DEBUG, "\tFamily: AF_INET (IPv4)");
+ TRACELOG(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr));
+ } break;
case AF_INET6:
{
- TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)");
- TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr));
- }
- break;
+ TRACELOG(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)");
+ TRACELOG(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr));
+ } break;
case AF_NETBIOS:
{
- TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)");
- }
- break;
- default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family);
- }
- break;
+ TRACELOG(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)");
+ } break;
+ default: TRACELOG(LOG_DEBUG, "\tFamily: Other %ld", family); break;
}
- TraceLog(LOG_DEBUG, "\tSocket type:");
+
+ TRACELOG(LOG_DEBUG, "\tSocket type:");
switch (socktype)
{
- case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break;
- case SOCK_STREAM:
- TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)");
- break;
- case SOCK_DGRAM:
- TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)");
- break;
- case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break;
- case SOCK_RDM:
- TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)");
- break;
- case SOCK_SEQPACKET:
- TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)");
- break;
- default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break;
- }
- TraceLog(LOG_DEBUG, "\tProtocol:");
+ case 0: TRACELOG(LOG_DEBUG, "\t- Unspecified"); break;
+ case SOCK_STREAM: TRACELOG(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); break;
+ case SOCK_DGRAM: TRACELOG(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); break;
+ case SOCK_RAW: TRACELOG(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break;
+ case SOCK_RDM: TRACELOG(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); break;
+ case SOCK_SEQPACKET: TRACELOG(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); break;
+ default: TRACELOG(LOG_DEBUG, "\t- Other %ld", socktype); break;
+ }
+
+ TRACELOG(LOG_DEBUG, "\tProtocol:");
switch (protocol)
{
- case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break;
- case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break;
- case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break;
- default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break;
+ case 0: TRACELOG(LOG_DEBUG, "\t- Unspecified"); break;
+ case IPPROTO_TCP: TRACELOG(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break;
+ case IPPROTO_UDP: TRACELOG(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break;
+ default: TRACELOG(LOG_DEBUG, "\t- Other %ld", protocol); break;
}
}
@@ -175,21 +161,23 @@ static const char *SocketAddressToString(struct sockaddr_storage *sockaddr)
//static const char* ipv6[INET6_ADDRSTRLEN];
assert(sockaddr != NULL);
assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6);
+
switch (sockaddr->ss_family)
{
case AF_INET:
{
- //struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr);
+ //struct sockaddr_in *s = ((struct sockaddr_in *)sockaddr);
//return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); // TODO.
}
break;
case AF_INET6:
{
- //struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr);
+ //struct sockaddr_in6 *s = ((struct sockaddr_in6 *)sockaddr);
//return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); // TODO.
}
break;
}
+
return NULL;
}
@@ -220,10 +208,10 @@ static void *GetSocketPortPtr(struct sockaddr_storage *sa)
{
if (sa->ss_family == AF_INET)
{
- return &(((struct sockaddr_in *) sa)->sin_port);
+ return &(((struct sockaddr_in *)sa)->sin_port);
}
- return &(((struct sockaddr_in6 *) sa)->sin6_port);
+ return &(((struct sockaddr_in6 *)sa)->sin6_port);
}
// Return a pointer to the address from the correct address family (IPv4, or IPv6)
@@ -231,10 +219,10 @@ static void *GetSocketAddressPtr(struct sockaddr_storage *sa)
{
if (sa->ss_family == AF_INET)
{
- return &(((struct sockaddr_in *) sa)->sin_addr);
+ return &(((struct sockaddr_in *)sa)->sin_addr);
}
- return &(((struct sockaddr_in6 *) sa)->sin6_addr);
+ return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
// Is the socket in a valid state?
@@ -244,6 +232,7 @@ static bool IsSocketValid(Socket *sock)
{
return (sock->channel != INVALID_SOCKET);
}
+
return false;
}
@@ -278,7 +267,7 @@ static char *SocketErrorCodeToString(int err)
{
#if defined(_WIN32)
static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE];
- sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err));
+ sTRACELOG(LOG_INFO, gaiStrErrorBuffer, "%s", gai_strerror(err));
return gaiStrErrorBuffer;
#else
return gai_strerror(err);
@@ -288,44 +277,30 @@ static char *SocketErrorCodeToString(int err)
// Set the defaults in the supplied SocketConfig if they're not already set
static bool SocketSetDefaults(SocketConfig *config)
{
- if (config->backlog_size == 0)
- {
- config->backlog_size = SOCKET_MAX_QUEUE_SIZE;
- }
+ if (config->backlog_size == 0) config->backlog_size = SOCKET_MAX_QUEUE_SIZE;
return true;
}
// Create the socket channel
-static bool InitSocket(Socket *sock, struct addrinfo *addr)
+static bool InitSocket(Socket *socket, struct addrinfo *address)
{
- switch (sock->type)
+ switch (socket->type)
{
case SOCKET_TCP:
- if (addr->ai_family == AF_INET)
- {
- sock->channel = socket(AF_INET, SOCK_STREAM, 0);
- }
- else
- {
- sock->channel = socket(AF_INET6, SOCK_STREAM, 0);
- }
- break;
+ {
+ if (address->ai_family == AF_INET) socket->channel = socket(AF_INET, SOCK_STREAM, 0);
+ else socket->channel = socket(AF_INET6, SOCK_STREAM, 0);
+ } break;
case SOCKET_UDP:
- if (addr->ai_family == AF_INET)
- {
- sock->channel = socket(AF_INET, SOCK_DGRAM, 0);
- }
- else
- {
- sock->channel = socket(AF_INET6, SOCK_DGRAM, 0);
- }
- break;
- default:
- TraceLog(LOG_WARNING, "Invalid socket type specified.");
- break;
+ {
+ if (address->ai_family == AF_INET) socket->channel = socket(AF_INET, SOCK_DGRAM, 0);
+ else socket->channel = socket(AF_INET6, SOCK_DGRAM, 0);
+ } break;
+ default: TRACELOG(LOG_WARNING, "Invalid socket type specified."); break;
}
- return IsSocketValid(sock);
+
+ return IsSocketValid(socket);
}
// CreateSocket() - Interally called by CreateSocket()
@@ -338,20 +313,21 @@ static bool InitSocket(Socket *sock, struct addrinfo *addr)
//
// e.g.
// SocketConfig server_config = { SocketConfig client_config = {
-// .host = "127.0.0.1", .host = "127.0.0.1",
-// .port = 8080, .port = 8080,
-// .server = true, };
+// .host = "127.0.0.1", .host = "127.0.0.1",
+// .port = 8080, .port = 8080,
+// .server = true, };
// .nonblocking = true,
// };
// SocketResult server_res; SocketResult client_res;
static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
{
- bool success = true;
- int addrstatus;
- struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
- struct addrinfo *res; // A pointer to the resulting address list
+ bool success = true;
+ int addrstatus;
+ struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
+ struct addrinfo *res; // A pointer to the resulting address list
+
outresult->socket->channel = INVALID_SOCKET;
- outresult->status = RESULT_FAILURE;
+ outresult->status = RESULT_FAILURE;
// Set the socket type
outresult->socket->type = config->type;
@@ -376,15 +352,10 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
if (addrstatus != 0)
{
outresult->socket->status = SocketGetLastError();
- TraceLog(LOG_WARNING,
- "Socket Error: %s",
- SocketErrorCodeToString(outresult->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->socket->status));
SocketSetLastError(0);
- TraceLog(LOG_WARNING,
- "Failed to get resolve host %s:%s: %s",
- config->host,
- config->port,
- SocketGetLastErrorString());
+ TRACELOG(LOG_WARNING, "Failed to get resolve host %s:%s: %s", config->host, config->port, SocketGetLastErrorString());
+
return (success = false);
}
else
@@ -392,8 +363,8 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];
//socklen_t client_len = sizeof(struct sockaddr_storage);
- //int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
- TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr);
+ //int rc = getnameinfo((struct sockaddr *)res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
+ TRACELOG(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr);
}
// Walk the address information linked-list
@@ -404,9 +375,7 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
if (!InitSocket(outresult->socket, it))
{
outresult->socket->status = SocketGetLastError();
- TraceLog(LOG_WARNING,
- "Socket Error: %s",
- SocketErrorCodeToString(outresult->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->socket->status));
SocketSetLastError(0);
continue;
}
@@ -415,11 +384,10 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
if (!SocketSetOptions(config, outresult->socket))
{
outresult->socket->status = SocketGetLastError();
- TraceLog(LOG_WARNING,
- "Socket Error: %s",
- SocketErrorCodeToString(outresult->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->socket->status));
SocketSetLastError(0);
freeaddrinfo(res);
+
return (success = false);
}
}
@@ -427,50 +395,49 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
if (!IsSocketValid(outresult->socket))
{
outresult->socket->status = SocketGetLastError();
- TraceLog(
- LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status));
SocketSetLastError(0);
freeaddrinfo(res);
+
return (success = false);
}
if (success)
{
- outresult->status = RESULT_SUCCESS;
- outresult->socket->ready = 0;
+ outresult->status = RESULT_SUCCESS;
+ outresult->socket->ready = 0;
outresult->socket->status = 0;
- if (!(config->type == SOCKET_UDP))
- {
- outresult->socket->isServer = config->server;
- }
+
+ if (!(config->type == SOCKET_UDP)) outresult->socket->isServer = config->server;
+
switch (res->ai_addr->sa_family)
{
case AF_INET:
{
- outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) RNET_MALLOC(
- sizeof(*outresult->socket->addripv4));
+ outresult->socket->addripv4 = (struct _SocketAddressIPv4 *)RNET_MALLOC(sizeof(*outresult->socket->addripv4));
+
if (outresult->socket->addripv4 != NULL)
{
- memset(outresult->socket->addripv4, 0,
- sizeof(*outresult->socket->addripv4));
+ memset(outresult->socket->addripv4, 0, sizeof(*outresult->socket->addripv4));
+
if (outresult->socket->addripv4 != NULL)
{
- memcpy(&outresult->socket->addripv4->address,
- (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in));
+ memcpy(&outresult->socket->addripv4->address, (struct sockaddr_in *)res->ai_addr, sizeof(struct sockaddr_in));
+
outresult->socket->isIPv6 = false;
- char hoststr[NI_MAXHOST];
- char portstr[NI_MAXSERV];
+ char hoststr[NI_MAXHOST];
+ char portstr[NI_MAXSERV];
+
socklen_t client_len = sizeof(struct sockaddr_storage);
- getnameinfo(
- (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
- TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr);
+ getnameinfo((struct sockaddr *)&outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
+
+ TRACELOG(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr);
}
}
- }
- break;
+ } break;
case AF_INET6:
{
- outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) RNET_MALLOC(
+ outresult->socket->addripv6 = (struct _SocketAddressIPv6 *)RNET_MALLOC(
sizeof(*outresult->socket->addripv6));
if (outresult->socket->addripv6 != NULL)
{
@@ -479,20 +446,21 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult)
if (outresult->socket->addripv6 != NULL)
{
memcpy(&outresult->socket->addripv6->address,
- (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6));
+ (struct sockaddr_in6 *)res->ai_addr, sizeof(struct sockaddr_in6));
outresult->socket->isIPv6 = true;
char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];
socklen_t client_len = sizeof(struct sockaddr_storage);
getnameinfo(
- (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
- TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr);
+ (struct sockaddr *)&outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
+ TRACELOG(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr);
}
}
- }
- break;
+ } break;
+ default: break;
}
}
+
freeaddrinfo(res);
return success;
}
@@ -503,12 +471,12 @@ static bool SocketSetBlocking(Socket *sock)
bool ret = true;
#if defined(_WIN32)
unsigned long mode = 0;
- ret = ioctlsocket(sock->channel, FIONBIO, &mode);
+ ret = ioctlsocket(sock->channel, FIONBIO, &mode);
#else
const int flags = fcntl(sock->channel, F_GETFL, 0);
if (!(flags & O_NONBLOCK))
{
- TraceLog(LOG_DEBUG, "Socket was already in blocking mode");
+ TRACELOG(LOG_DEBUG, "Socket was already in blocking mode");
return ret;
}
@@ -523,14 +491,16 @@ static bool SocketSetNonBlocking(Socket *sock)
bool ret = true;
#if defined(_WIN32)
unsigned long mode = 1;
- ret = ioctlsocket(sock->channel, FIONBIO, &mode);
+ ret = ioctlsocket(sock->channel, FIONBIO, &mode);
#else
const int flags = fcntl(sock->channel, F_GETFL, 0);
+
if ((flags & O_NONBLOCK))
{
- TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode");
+ TRACELOG(LOG_DEBUG, "Socket was already in non-blocking mode");
return ret;
}
+
ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK)));
#endif
return ret;
@@ -542,15 +512,10 @@ static bool SocketSetOptions(SocketConfig *config, Socket *sock)
for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++)
{
SocketOpt *opt = &config->sockopts[i];
- if (opt->id == 0)
- {
- break;
- }
- if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0)
- {
- return false;
- }
+ if (opt->id == 0) break;
+
+ if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) return false;
}
return true;
@@ -559,10 +524,8 @@ static bool SocketSetOptions(SocketConfig *config, Socket *sock)
// Set "hints" in an addrinfo struct, to be passed to getaddrinfo.
static void SocketSetHints(SocketConfig *config, struct addrinfo *hints)
{
- if (config == NULL || hints == NULL)
- {
- return;
- }
+ if (config == NULL || hints == NULL) return;
+
memset(hints, 0, sizeof(*hints));
// Check if the ip supplied in the config is a valid ipv4 ip ipv6 address
@@ -578,26 +541,15 @@ static void SocketSetHints(SocketConfig *config, struct addrinfo *hints)
hints->ai_family = AF_INET6;
hints->ai_flags |= AI_NUMERICHOST;
}
- else
- {
- hints->ai_family = AF_UNSPEC;
- }
+ else hints->ai_family = AF_UNSPEC;
}
- if (config->type == SOCKET_UDP)
- {
- hints->ai_socktype = SOCK_DGRAM;
- }
- else
- {
- hints->ai_socktype = SOCK_STREAM;
- }
+ if (config->type == SOCKET_UDP) hints->ai_socktype = SOCK_DGRAM;
+ else hints->ai_socktype = SOCK_STREAM;
+
// Set passive unless UDP client
- if (!(config->type == SOCKET_UDP) || config->server)
- {
- hints->ai_flags = AI_PASSIVE;
- }
+ if (!(config->type == SOCKET_UDP) || config->server) hints->ai_flags = AI_PASSIVE;
}
//----------------------------------------------------------------------------------
@@ -608,25 +560,22 @@ static void SocketSetHints(SocketConfig *config, struct addrinfo *hints)
bool InitNetwork()
{
#if defined(_WIN32)
- WORD wVersionRequested;
+ WORD wVersionRequested;
WSADATA wsaData;
- int err;
wVersionRequested = MAKEWORD(2, 2);
- err = WSAStartup(wVersionRequested, &wsaData);
+ int err = WSAStartup(wVersionRequested, &wsaData);
+
if (err != 0)
{
- TraceLog(LOG_WARNING, "WinSock failed to initialise.");
+ TRACELOG(LOG_WARNING, "WinSock failed to initialise.");
return false;
}
- else
- {
- TraceLog(LOG_INFO, "WinSock initialised.");
- }
+ else TRACELOG(LOG_INFO, "WinSock initialised.");
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
- TraceLog(LOG_WARNING, "WinSock failed to initialise.");
+ TRACELOG(LOG_WARNING, "WinSock failed to initialise.");
WSACleanup();
return false;
}
@@ -653,17 +602,17 @@ void CloseNetwork()
// The following flags are available:
//
// NAME_INFO_DEFAULT 0x00 // No flags set
-// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts
+// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts
// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address
-// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS
+// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS
// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #)
-// NAME_INFO_DGRAM 0x10 // Service is a datagram service
+// NAME_INFO_DGRAM 0x10 // Service is a datagram service
void ResolveIP(const char *ip, const char *port, int flags, char *host, char *serv)
{
// Variables
- int status; // Status value to return (0) is success
- struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
- struct addrinfo *res; // A pointer to the resulting address list
+ int status; // Status value to return (0) is success
+ struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
+ struct addrinfo *res; // A pointer to the resulting address list
// Set the hints
memset(&hints, 0, sizeof hints);
@@ -678,45 +627,31 @@ void ResolveIP(const char *ip, const char *port, int flags, char *host, char *se
);
// Did we succeed?
- if (status != 0)
- {
- TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno));
- }
- else
- {
- TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port);
- }
+ if (status != 0) TRACELOG(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno));
+ else TRACELOG(LOG_DEBUG, "Resolving... %s::%s", ip, port);
// Attempt to resolve network byte order ip to hostname
switch (res->ai_family)
{
case AF_INET:
- status = getnameinfo(&*((struct sockaddr *) res->ai_addr),
- sizeof(*((struct sockaddr_in *) res->ai_addr)),
- host,
- NI_MAXHOST,
- serv,
- NI_MAXSERV,
- flags);
- break;
+ {
+ status = getnameinfo(&*((struct sockaddr *)res->ai_addr),
+ sizeof(*((struct sockaddr_in *)res->ai_addr)),
+ host, NI_MAXHOST, serv, NI_MAXSERV, flags);
+ } break;
case AF_INET6:
+ {
/*
- status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), // TODO.
- sizeof(*((struct sockaddr_in6 *) res->ai_addr)),
+ status = getnameinfo(&*((struct sockaddr_in6 *)res->ai_addr), // TODO.
+ sizeof(*((struct sockaddr_in6 *)res->ai_addr)),
host, NI_MAXHOST, serv, NI_MAXSERV, flags);
*/
- break;
+ } break;
default: break;
}
- if (status != 0)
- {
- TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString());
- }
- else
- {
- TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host);
- }
+ if (status != 0) TRACELOG(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString());
+ else TRACELOG(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host);
// Free the pointer to the data returned by addrinfo
freeaddrinfo(res);
@@ -725,8 +660,8 @@ void ResolveIP(const char *ip, const char *port, int flags, char *host, char *se
// Protocol-independent translation from an ANSI host name to an address
//
// e.g.
-// const char* address = "127.0.0.1" (local address)
-// const char* port = "80"
+// const char* address = "127.0.0.1" (local address)
+// const char* port = "80"
//
// Parameters:
// const char* address - A pointer to a NULL-terminated ANSI string that contains a host (node) name or a numeric host address string.
@@ -738,8 +673,8 @@ void ResolveIP(const char *ip, const char *port, int flags, char *host, char *se
int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr)
{
// Variables
- int status; // Status value to return (0) is success
- struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
+ int status; // Status value to return (0) is success
+ struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?)
struct addrinfo *res; // will point to the results
struct addrinfo *iterator;
assert(((address != NULL || address != 0) || (service != NULL || service != 0)));
@@ -758,13 +693,10 @@ int ResolveHost(const char *address, const char *service, int addressType, int f
// When the address is NULL, populate the IP for me
if (address == NULL)
{
- if ((hints.ai_flags & AI_PASSIVE) == 0)
- {
- hints.ai_flags |= AI_PASSIVE;
- }
+ if ((hints.ai_flags & AI_PASSIVE) == 0) hints.ai_flags |= AI_PASSIVE;
}
- TraceLog(LOG_INFO, "Resolving host...");
+ TRACELOG(LOG_INFO, "Resolving host...");
// Populate address information
status = getaddrinfo(address, // e.g. "www.example.com" or IP
@@ -778,33 +710,24 @@ int ResolveHost(const char *address, const char *service, int addressType, int f
{
int error = SocketGetLastError();
SocketSetLastError(0);
- TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error));
+ TRACELOG(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error));
return -1;
}
- else
- {
- TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service);
- }
+ else TRACELOG(LOG_INFO, "Successfully resolved host %s:%s", address, service);
// Calculate the size of the address information list
int size = 0;
- for (iterator = res; iterator != NULL; iterator = iterator->ai_next)
- {
- size++;
- }
+ for (iterator = res; iterator != NULL; iterator = iterator->ai_next) size++;
// Validate the size is > 0, otherwise return
if (size <= 0)
{
- TraceLog(LOG_WARNING, "Error, no addresses found.");
+ TRACELOG(LOG_WARNING, "Error, no addresses found.");
return -1;
}
// If not address list was allocated, allocate it dynamically with the known address size
- if (outAddr == NULL)
- {
- outAddr = (AddressInformation *) RNET_MALLOC(size * sizeof(AddressInformation));
- }
+ if (outAddr == NULL) outAddr = (AddressInformation *)RNET_MALLOC(size * sizeof(AddressInformation));
// Dynamically allocate an array of address information structs
if (outAddr != NULL)
@@ -818,16 +741,13 @@ int ResolveHost(const char *address, const char *service, int addressType, int f
break;
}
}
+
outAddr[i] = NULL;
- if (i != size)
- {
- outAddr = NULL;
- }
+ if (i != size) outAddr = NULL;
}
else
{
- TraceLog(LOG_WARNING,
- "Error, failed to dynamically allocate memory for the address list");
+ TRACELOG(LOG_WARNING, "Error, failed to dynamically allocate memory for the address list");
return -1;
}
@@ -837,18 +757,18 @@ int ResolveHost(const char *address, const char *service, int addressType, int f
{
if (i < size)
{
- outAddr[i]->addr.ai_flags = iterator->ai_flags;
- outAddr[i]->addr.ai_family = iterator->ai_family;
+ outAddr[i]->addr.ai_flags = iterator->ai_flags;
+ outAddr[i]->addr.ai_family = iterator->ai_family;
outAddr[i]->addr.ai_socktype = iterator->ai_socktype;
outAddr[i]->addr.ai_protocol = iterator->ai_protocol;
- outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen;
- *outAddr[i]->addr.ai_addr = *iterator->ai_addr;
+ outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen;
+ *outAddr[i]->addr.ai_addr = *iterator->ai_addr;
#if NET_DEBUG_ENABLED
- TraceLog(LOG_DEBUG, "GetAddressInformation");
- TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags);
+ TRACELOG(LOG_DEBUG, "GetAddressInformation");
+ TRACELOG(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags);
//PrintSocket(outAddr[i]->addr.ai_addr, outAddr[i]->addr.ai_family, outAddr[i]->addr.ai_socktype, outAddr[i]->addr.ai_protocol);
- TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen);
- TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname);
+ TRACELOG(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen);
+ TRACELOG(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname);
#endif
i++;
}
@@ -869,9 +789,9 @@ int ResolveHost(const char *address, const char *service, int addressType, int f
//
// e.g.
// SocketConfig server_config = { SocketConfig client_config = {
-// .host = "127.0.0.1", .host = "127.0.0.1",
-// .port = 8080, .port = 8080,
-// .server = true, };
+// .host = "127.0.0.1", .host = "127.0.0.1",
+// .port = 8080, .port = 8080,
+// .server = true, };
// .nonblocking = true,
// };
// SocketResult server_res; SocketResult client_res;
@@ -881,15 +801,12 @@ bool SocketCreate(SocketConfig *config, SocketResult *result)
bool success = true;
// Make sure we've not received a null config or result pointer
- if (config == NULL || result == NULL)
- {
- return (success = false);
- }
+ if (config == NULL || result == NULL) return (success = false);
// Set the defaults based on the config
if (!SocketSetDefaults(config))
{
- TraceLog(LOG_WARNING, "Configuration Error.");
+ TRACELOG(LOG_WARNING, "Configuration Error.");
success = false;
}
else
@@ -897,20 +814,12 @@ bool SocketCreate(SocketConfig *config, SocketResult *result)
// Create the socket
if (CreateSocket(config, result))
{
- if (config->nonblocking)
- {
- SocketSetNonBlocking(result->socket);
- }
- else
- {
- SocketSetBlocking(result->socket);
- }
- }
- else
- {
- success = false;
+ if (config->nonblocking) SocketSetNonBlocking(result->socket);
+ else SocketSetBlocking(result->socket);
}
+ else success = false;
}
+
return success;
}
@@ -918,70 +827,61 @@ bool SocketCreate(SocketConfig *config, SocketResult *result)
// Note: The bind function is required on an unconnected socket before subsequent calls to the listen function.
bool SocketBind(SocketConfig *config, SocketResult *result)
{
- bool success = false;
- result->status = RESULT_FAILURE;
+ bool success = false;
+ result->status = RESULT_FAILURE;
struct sockaddr_storage *sock_addr = NULL;
// Don't bind to a socket that isn't configured as a server
if (!IsSocketValid(result->socket) || !config->server)
{
- TraceLog(LOG_WARNING,
- "Cannot bind to socket marked as \"Client\" in SocketConfig.");
+ TRACELOG(LOG_WARNING, Cannot bind to socket marked as \"Client\" in SocketConfig.");
success = false;
}
else
{
- if (result->socket->isIPv6)
- {
- sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address;
- }
- else
- {
- sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address;
- }
+ if (result->socket->isIPv6) sock_addr = (struct sockaddr_storage *)&result->socket->addripv6->address;
+ else sock_addr = (struct sockaddr_storage *)&result->socket->addripv4->address;
+
if (sock_addr != NULL)
{
- if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR)
+ if (bind(result->socket->channel, (struct sockaddr *)sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR)
{
- TraceLog(LOG_INFO, "Successfully bound socket.");
+ TRACELOG(LOG_INFO, "Successfully bound socket.");
success = true;
}
else
{
result->socket->status = SocketGetLastError();
- TraceLog(LOG_WARNING, "Socket Error: %s",
- SocketErrorCodeToString(result->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(result->socket->status));
SocketSetLastError(0);
success = false;
}
}
}
+
// Was the bind a success?
if (success)
{
- result->status = RESULT_SUCCESS;
- result->socket->ready = 0;
+ result->status = RESULT_SUCCESS;
+ result->socket->ready = 0;
result->socket->status = 0;
- socklen_t sock_len = sizeof(*sock_addr);
- if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0)
+ socklen_t sock_len = sizeof(*sock_addr);
+
+ if (getsockname(result->socket->channel, (struct sockaddr *)sock_addr, &sock_len) < 0)
{
- TraceLog(LOG_WARNING, "Couldn't get socket address");
+ TRACELOG(LOG_WARNING, "Couldn't get socket address");
}
else
{
- struct sockaddr_in *s = (struct sockaddr_in *) sock_addr;
+ struct sockaddr_in *s = (struct sockaddr_in *)sock_addr;
// result->socket->address.host = s->sin_addr.s_addr;
// result->socket->address.port = s->sin_port;
- //
- result->socket->addripv4
- = (struct _SocketAddressIPv4 *) RNET_MALLOC(sizeof(*result->socket->addripv4));
- if (result->socket->addripv4 != NULL)
- {
- memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4));
- }
- memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in));
- //
+ result->socket->addripv4 = (struct _SocketAddressIPv4 *)RNET_MALLOC(sizeof(*result->socket->addripv4));
+
+ if (result->socket->addripv4 != NULL) memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4));
+
+ memcpy(&result->socket->addripv4->address, (struct sockaddr_in *)&s->sin_addr, sizeof(struct sockaddr_in));
}
}
return success;
@@ -990,14 +890,13 @@ bool SocketBind(SocketConfig *config, SocketResult *result)
// Listens (and queues) incoming connections requests for a bound port.
bool SocketListen(SocketConfig *config, SocketResult *result)
{
- bool success = false;
+ bool success = false;
result->status = RESULT_FAILURE;
// Don't bind to a socket that isn't configured as a server
if (!IsSocketValid(result->socket) || !config->server)
{
- TraceLog(LOG_WARNING,
- "Cannot listen on socket marked as \"Client\" in SocketConfig.");
+ TRACELOG(LOG_WARNING, "Cannot listen on socket marked as \"Client\" in SocketConfig.");
success = false;
}
else
@@ -1007,22 +906,20 @@ bool SocketListen(SocketConfig *config, SocketResult *result)
{
if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR)
{
- TraceLog(LOG_INFO, "Started listening on socket...");
+ TRACELOG(LOG_INFO, "Started listening on socket...");
success = true;
}
else
{
success = false;
result->socket->status = SocketGetLastError();
- TraceLog(LOG_WARNING, "Socket Error: %s",
- SocketErrorCodeToString(result->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(result->socket->status));
SocketSetLastError(0);
}
}
else
{
- TraceLog(LOG_WARNING,
- "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig.");
+ TRACELOG(LOG_WARNING, "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig.");
success = false;
}
}
@@ -1030,24 +927,24 @@ bool SocketListen(SocketConfig *config, SocketResult *result)
// Was the listen a success?
if (success)
{
- result->status = RESULT_SUCCESS;
- result->socket->ready = 0;
+ result->status = RESULT_SUCCESS;
+ result->socket->ready = 0;
result->socket->status = 0;
}
+
return success;
}
// Connect the socket to the destination specified by "host" and "port" in SocketConfig
bool SocketConnect(SocketConfig *config, SocketResult *result)
{
- bool success = true;
+ bool success = true;
result->status = RESULT_FAILURE;
// Only bind to sockets marked as server
if (config->server)
{
- TraceLog(LOG_WARNING,
- "Cannot connect to socket marked as \"Server\" in SocketConfig.");
+ TRACELOG(LOG_WARNING, "Cannot connect to socket marked as \"Server\" in SocketConfig.");
success = false;
}
else
@@ -1057,36 +954,32 @@ bool SocketConnect(SocketConfig *config, SocketResult *result)
struct sockaddr_in ip4addr;
ip4addr.sin_family = AF_INET;
unsigned long hport;
- hport = strtoul(config->port, NULL, 0);
+ hport = strtoul(config->port, NULL, 0);
ip4addr.sin_port = htons(hport);
-
+
// TODO: Changed the code to avoid the usage of inet_pton and inet_ntop replacing them with getnameinfo (that should have a better support on windows).
-
+
//inet_pton(AF_INET, config->host, &ip4addr.sin_addr);
- int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr));
+ int connect_result = connect(result->socket->channel, (struct sockaddr *)&ip4addr, sizeof(ip4addr));
+
if (connect_result == SOCKET_ERROR)
{
result->socket->status = SocketGetLastError();
SocketSetLastError(0);
+
switch (result->socket->status)
{
- case WSAEWOULDBLOCK:
- {
- success = true;
- break;
- }
+ case WSAEWOULDBLOCK: success = true; break;
default:
{
- TraceLog(LOG_WARNING, "Socket Error: %s",
- SocketErrorCodeToString(result->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(result->socket->status));
success = false;
- break;
- }
+ } break;
}
}
else
{
- TraceLog(LOG_INFO, "Successfully connected to socket.");
+ TRACELOG(LOG_INFO, "Successfully connected to socket.");
success = true;
}
}
@@ -1097,33 +990,29 @@ bool SocketConnect(SocketConfig *config, SocketResult *result)
struct sockaddr_in6 ip6addr;
ip6addr.sin6_family = AF_INET6;
unsigned long hport;
- hport = strtoul(config->port, NULL, 0);
+ hport = strtoul(config->port, NULL, 0);
ip6addr.sin6_port = htons(hport);
//inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); // TODO.
- int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr));
+ int connect_result = connect(result->socket->channel, (struct sockaddr *)&ip6addr, sizeof(ip6addr));
+
if (connect_result == SOCKET_ERROR)
{
result->socket->status = SocketGetLastError();
SocketSetLastError(0);
+
switch (result->socket->status)
{
- case WSAEWOULDBLOCK:
- {
- success = true;
- break;
- }
+ case WSAEWOULDBLOCK: success = true; break;
default:
{
- TraceLog(LOG_WARNING, "Socket Error: %s",
- SocketErrorCodeToString(result->socket->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(result->socket->status));
success = false;
- break;
- }
+ } break;
}
}
else
{
- TraceLog(LOG_INFO, "Successfully connected to socket.");
+ TRACELOG(LOG_INFO, "Successfully connected to socket.");
success = true;
}
}
@@ -1132,8 +1021,8 @@ bool SocketConnect(SocketConfig *config, SocketResult *result)
if (success)
{
- result->status = RESULT_SUCCESS;
- result->socket->ready = 0;
+ result->status = RESULT_SUCCESS;
+ result->socket->ready = 0;
result->socket->status = 0;
}
@@ -1147,10 +1036,7 @@ void SocketClose(Socket *sock)
{
if (sock != NULL)
{
- if (sock->channel != INVALID_SOCKET)
- {
- closesocket(sock->channel);
- }
+ if (sock->channel != INVALID_SOCKET) closesocket(sock->channel);
}
}
@@ -1163,7 +1049,7 @@ SocketAddressStorage SocketGetPeerAddress(Socket *sock)
if (sock->isIPv6) return sock->addripv6;
else return sock->addripv4;
*/
-
+
return NULL;
}
@@ -1171,14 +1057,14 @@ SocketAddressStorage SocketGetPeerAddress(Socket *sock)
char *GetSocketAddressHost(SocketAddressStorage storage)
{
assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6);
- return SocketAddressToString((struct sockaddr_storage *) storage);
+ return SocketAddressToString((struct sockaddr_storage *)storage);
}
// Return the address-type appropriate port(service) portion of a socket address
short GetSocketAddressPort(SocketAddressStorage storage)
{
//return ntohs(GetSocketPortPtr(storage)); // TODO.
-
+
return 0;
}
@@ -1200,58 +1086,58 @@ short GetSocketAddressPort(SocketAddressStorage storage)
// }
Socket *SocketAccept(Socket *server, SocketConfig *config)
{
- if (!server->isServer || server->type == SOCKET_UDP)
- {
- return NULL;
- }
+ if (!server->isServer || server->type == SOCKET_UDP) return NULL;
+
struct sockaddr_storage sock_addr;
- socklen_t sock_alen;
- Socket * sock;
- sock = AllocSocket();
+ socklen_t sock_alen;
+ Socket *sock = AllocSocket();
server->ready = 0;
- sock_alen = sizeof(sock_addr);
- sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen);
+ sock_alen = sizeof(sock_addr);
+ sock->channel = accept(server->channel, (struct sockaddr *)&sock_addr, &sock_alen);
+
if (sock->channel == INVALID_SOCKET)
{
sock->status = SocketGetLastError();
- TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status));
SocketSetLastError(0);
SocketClose(sock);
+
return NULL;
}
+
(config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock);
sock->isServer = false;
- sock->ready = 0;
- sock->type = server->type;
+ sock->ready = 0;
+ sock->type = server->type;
+
switch (sock_addr.ss_family)
{
case AF_INET:
{
- struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr);
- sock->addripv4 = (struct _SocketAddressIPv4 *) RNET_MALLOC(sizeof(*sock->addripv4));
+ struct sockaddr_in *s = ((struct sockaddr_in *)&sock_addr);
+ sock->addripv4 = (struct _SocketAddressIPv4 *)RNET_MALLOC(sizeof(*sock->addripv4));
+
if (sock->addripv4 != NULL)
{
memset(sock->addripv4, 0, sizeof(*sock->addripv4));
- memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in));
- TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s),
- ntohs(sock->addripv4->address.sin_port));
+ memcpy(&sock->addripv4->address, (struct sockaddr_in *)&s->sin_addr, sizeof(struct sockaddr_in));
+ TRACELOG(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *)s), ntohs(sock->addripv4->address.sin_port));
}
- }
- break;
+ } break;
case AF_INET6:
{
- struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr);
- sock->addripv6 = (struct _SocketAddressIPv6 *) RNET_MALLOC(sizeof(*sock->addripv6));
+ struct sockaddr_in6 *s = ((struct sockaddr_in6 *)&sock_addr);
+ sock->addripv6 = (struct _SocketAddressIPv6 *)RNET_MALLOC(sizeof(*sock->addripv6));
+
if (sock->addripv6 != NULL)
{
memset(sock->addripv6, 0, sizeof(*sock->addripv6));
- memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6));
- TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s),
- ntohs(sock->addripv6->address.sin6_port));
+ memcpy(&sock->addripv6->address, (struct sockaddr_in6 *)&s->sin6_addr, sizeof(struct sockaddr_in6));
+ TRACELOG(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *)s), ntohs(sock->addripv6->address.sin6_port));
}
- }
- break;
+ } break;
}
+
return sock;
}
@@ -1260,9 +1146,10 @@ static int ValidChannel(int channel)
{
if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS))
{
- TraceLog(LOG_WARNING, "Invalid channel");
+ TRACELOG(LOG_WARNING, "Invalid channel");
return 0;
}
+
return 1;
}
@@ -1270,46 +1157,43 @@ static int ValidChannel(int channel)
int SocketSetChannel(Socket *socket, int channel, const IPAddress *address)
{
struct UDPChannel *binding;
+
if (socket == NULL)
{
- TraceLog(LOG_WARNING, "Passed a NULL socket");
+ TRACELOG(LOG_WARNING, "Passed a NULL socket");
return (-1);
}
+
if (channel == -1)
{
for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel)
{
binding = &socket->binding[channel];
- if (binding->numbound < SOCKET_MAX_UDPADDRESSES)
- {
- break;
- }
+ if (binding->numbound < SOCKET_MAX_UDPADDRESSES) break;
}
}
else
{
- if (!ValidChannel(channel))
- {
- return (-1);
- }
+ if (!ValidChannel(channel)) return (-1);
+
binding = &socket->binding[channel];
}
+
if (binding->numbound == SOCKET_MAX_UDPADDRESSES)
{
- TraceLog(LOG_WARNING, "No room for new addresses");
+ TRACELOG(LOG_WARNING, "No room for new addresses");
return (-1);
}
+
binding->address[binding->numbound++] = *address;
+
return (channel);
}
// Remove the socket channel
void SocketUnsetChannel(Socket *socket, int channel)
{
- if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS))
- {
- socket->binding[channel].numbound = 0;
- }
+ if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) socket->binding[channel].numbound = 0;
}
/* Allocate/free a single UDP packet 'size' bytes long.
@@ -1317,39 +1201,39 @@ void SocketUnsetChannel(Socket *socket, int channel)
*/
SocketDataPacket *AllocPacket(int size)
{
- SocketDataPacket *packet;
- int error;
+ SocketDataPacket *packet = (SocketDataPacket *)RNET_MALLOC(sizeof(*packet));
+ int error = 1;
- error = 1;
- packet = (SocketDataPacket *) RNET_MALLOC(sizeof(*packet));
if (packet != NULL)
{
packet->maxlen = size;
- packet->data = (uint8_t *) RNET_MALLOC(size);
+ packet->data = (uint8_t *)RNET_MALLOC(size);
if (packet->data != NULL)
{
error = 0;
}
}
+
if (error)
{
FreePacket(packet);
packet = NULL;
}
+
return (packet);
}
int ResizePacket(SocketDataPacket *packet, int newsize)
{
- uint8_t *newdata;
+ uint8_t *newdata = (uint8_t *)RNET_MALLOC(newsize);
- newdata = (uint8_t *) RNET_MALLOC(newsize);
if (newdata != NULL)
{
RNET_FREE(packet->data);
- packet->data = newdata;
+ packet->data = newdata;
packet->maxlen = newsize;
}
+
return (packet->maxlen);
}
@@ -1362,16 +1246,12 @@ void FreePacket(SocketDataPacket *packet)
}
}
-/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets,
- each 'size' bytes long.
- A pointer to the packet array is returned, or NULL if the function ran out
- of memory.
- */
+// Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, each 'size' bytes long.
+// A pointer to the packet array is returned, or NULL if the function ran out of memory.
SocketDataPacket **AllocPacketList(int howmany, int size)
{
- SocketDataPacket **packetV;
+ SocketDataPacket **packetV = (SocketDataPacket **)RNET_MALLOC((howmany + 1) * sizeof(*packetV));
- packetV = (SocketDataPacket **) RNET_MALLOC((howmany + 1) * sizeof(*packetV));
if (packetV != NULL)
{
int i;
@@ -1386,11 +1266,12 @@ SocketDataPacket **AllocPacketList(int howmany, int size)
packetV[i] = NULL;
if (i != howmany)
- {
+ {
FreePacketList(packetV);
packetV = NULL;
}
}
+
return (packetV);
}
@@ -1398,30 +1279,24 @@ void FreePacketList(SocketDataPacket **packetV)
{
if (packetV)
{
- int i;
- for (i = 0; packetV[i]; ++i)
- {
- FreePacket(packetV[i]);
- }
+ for (int i = 0; packetV[i]; ++i) FreePacket(packetV[i]);
RNET_FREE(packetV);
}
}
-// Send 'len' bytes of 'data' over the non-server socket 'sock'
-//
-// Example
+// Send 'len' bytes of 'data' over the non-server socket 'sock'
int SocketSend(Socket *sock, const void *datap, int length)
{
- int sent = 0;
- int left = length;
- int status = -1;
- int numsent = 0;
- const unsigned char *data = (const unsigned char *) datap;
+ int sent = 0;
+ int left = length;
+ int status = -1;
+ int numsent = 0;
+ const unsigned char *data = (const unsigned char *)datap;
// Server sockets are for accepting connections only
if (sock->isServer)
{
- TraceLog(LOG_WARNING, "Cannot send information on a server socket");
+ TRACELOG(LOG_WARNING, "Cannot send information on a server socket");
return -1;
}
@@ -1433,7 +1308,7 @@ int SocketSend(Socket *sock, const void *datap, int length)
SocketSetLastError(0);
do
{
- length = send(sock->channel, (const char *) data, left, 0);
+ length = send(sock->channel, (const char *)data, left, 0);
if (length > 0)
{
sent += length;
@@ -1448,50 +1323,39 @@ int SocketSend(Socket *sock, const void *datap, int length)
if (length == SOCKET_ERROR)
{
sock->status = SocketGetLastError();
- TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status));
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status));
SocketSetLastError(0);
}
- else
- {
- TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent);
- }
+ else TRACELOG(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent);
return sent;
- }
- break;
+ } break;
case SOCKET_UDP:
{
SocketSetLastError(0);
- if (sock->isIPv6)
- {
- status = sendto(sock->channel, (const char *) data, left, 0,
- (struct sockaddr *) &sock->addripv6->address,
- sizeof(sock->addripv6->address));
- }
- else
- {
- status = sendto(sock->channel, (const char *) data, left, 0,
- (struct sockaddr *) &sock->addripv4->address,
- sizeof(sock->addripv4->address));
- }
+
+ if (sock->isIPv6) status = sendto(sock->channel, (const char *)data, left, 0, (struct sockaddr *)&sock->addripv6->address, sizeof(sock->addripv6->address));
+ else status = sendto(sock->channel, (const char *)data, left, 0, (struct sockaddr *)&sock->addripv4->address, sizeof(sock->addripv4->address));
+
if (sent >= 0)
{
sock->status = 0;
++numsent;
- TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status);
+ TRACELOG(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status);
}
else
{
sock->status = SocketGetLastError();
- TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status));
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status));
SocketSetLastError(0);
return 0;
}
+
return numsent;
- }
- break;
+ } break;
default: break;
}
+
return -1;
}
@@ -1510,10 +1374,10 @@ int SocketReceive(Socket *sock, void *data, int maxlen)
//char ip[INET6_ADDRSTRLEN];
// Server sockets are for accepting connections only
- if (sock->isServer && sock->type == SOCKET_TCP)
+ if (sock->isServer && (sock->type == SOCKET_TCP))
{
sock->status = SocketGetLastError();
- TraceLog(LOG_DEBUG, "Socket Error: %s", "Server sockets cannot be used to receive data");
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", "Server sockets cannot be used to receive data");
SocketSetLastError(0);
return 0;
}
@@ -1526,7 +1390,7 @@ int SocketReceive(Socket *sock, void *data, int maxlen)
SocketSetLastError(0);
do
{
- len = recv(sock->channel, (char *) data, maxlen, 0);
+ len = recv(sock->channel, (char *)data, maxlen, 0);
} while (SocketGetLastError() == WSAEINTR);
if (len > 0)
@@ -1534,53 +1398,49 @@ int SocketReceive(Socket *sock, void *data, int maxlen)
// Who sent the packet?
if (sock->type == SOCKET_UDP)
{
- //TraceLog(LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip)));
+ //TRACELOG(LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *)&sock_addr), ip, sizeof(ip)));
}
-
- ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream
- TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len);
+
+ ((unsigned char *)data)[len] = '\0'; // Add null terminating character to the end of the stream
+ TRACELOG(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len);
}
-
+
sock->ready = 0;
return len;
- }
- break;
+ } break;
case SOCKET_UDP:
{
SocketSetLastError(0);
sock_len = sizeof(sock_addr);
- status = recvfrom(sock->channel, // The receving channel
- data, // A pointer to the data buffer to fill
- maxlen, // The max length of the data to fill
- 0, // Flags
- (struct sockaddr *) &sock_addr, // The address of the recevied data
- &sock_len // The length of the received data address
+ status = recvfrom(sock->channel, // The receving channel
+ data, // A pointer to the data buffer to fill
+ maxlen, // The max length of the data to fill
+ 0, // Flags
+ (struct sockaddr *)&sock_addr, // The address of the recevied data
+ &sock_len // The length of the received data address
);
- if (status >= 0)
- {
- ++numrecv;
- }
+
+ if (status >= 0) ++numrecv;
else
{
sock->status = SocketGetLastError();
+
switch (sock->status)
{
- case WSAEWOULDBLOCK: { break;
- }
- default:
- {
- TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status));
- break;
- }
+ case WSAEWOULDBLOCK: break;
+ default: TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); break;
}
+
SocketSetLastError(0);
return 0;
}
+
sock->ready = 0;
return numrecv;
- }
- break;
+ } break;
+ default: break;
}
+
return -1;
}
@@ -1598,26 +1458,19 @@ bool IsSocketConnected(Socket *sock)
FD_ZERO(&writefds);
FD_SET(sock->channel, &writefds);
struct timeval timeout;
- timeout.tv_sec = 1;
+ timeout.tv_sec = 1;
timeout.tv_usec = 1000000000UL;
- int total = select(0, NULL, &writefds, NULL, &timeout);
+ int total = select(0, NULL, &writefds, NULL, &timeout);
+
if (total == -1)
{ // Error
sock->status = SocketGetLastError();
- TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status));
SocketSetLastError(0);
}
- else if (total == 0)
- { // Timeout
- return false;
- }
- else
- {
- if (FD_ISSET(sock->channel, &writefds))
- {
- return true;
- }
- }
+ else if (total == 0) return false; // Timeout
+ else if (FD_ISSET(sock->channel, &writefds)) return true;
+
return false;
#else
return true;
@@ -1627,8 +1480,8 @@ bool IsSocketConnected(Socket *sock)
// Allocate and return a SocketResult struct
SocketResult *AllocSocketResult()
{
- struct SocketResult *res;
- res = (struct SocketResult *) RNET_MALLOC(sizeof(*res));
+ struct SocketResult *res = (struct SocketResult *)RNET_MALLOC(sizeof(*res));
+
if (res != NULL)
{
memset(res, 0, sizeof(*res));
@@ -1638,6 +1491,7 @@ SocketResult *AllocSocketResult()
res = NULL;
}
}
+
return res;
}
@@ -1646,10 +1500,8 @@ void FreeSocketResult(SocketResult **result)
{
if (*result != NULL)
{
- if ((*result)->socket != NULL)
- {
- FreeSocket(&((*result)->socket));
- }
+ if ((*result)->socket != NULL) FreeSocket(&((*result)->socket));
+
RNET_FREE(*result);
*result = NULL;
}
@@ -1658,21 +1510,18 @@ void FreeSocketResult(SocketResult **result)
// Allocate a Socket
Socket *AllocSocket()
{
- // Allocate a socket if one already hasn't been
struct Socket *sock;
- sock = (Socket *) RNET_MALLOC(sizeof(*sock));
- if (sock != NULL)
- {
- memset(sock, 0, sizeof(*sock));
- }
+ sock = (Socket *)RNET_MALLOC(sizeof(*sock));
+
+ if (sock != NULL) memset(sock, 0, sizeof(*sock));
else
{
- TraceLog(
- LOG_WARNING, "Ran out of memory attempting to allocate a socket");
+ TRACELOG(LOG_WARNING, "Ran out of memory attempting to allocate a socket");
SocketClose(sock);
RNET_FREE(sock);
sock = NULL;
}
+
return sock;
}
@@ -1689,21 +1538,16 @@ void FreeSocket(Socket **sock)
// Allocate a SocketSet
SocketSet *AllocSocketSet(int max)
{
- struct SocketSet *set;
- int i;
+ struct SocketSet *set = (struct SocketSet *)RNET_MALLOC(sizeof(*set));
- set = (struct SocketSet *) RNET_MALLOC(sizeof(*set));
if (set != NULL)
{
set->numsockets = 0;
set->maxsockets = max;
- set->sockets = (struct Socket **) RNET_MALLOC(max * sizeof(*set->sockets));
+ set->sockets = (struct Socket **)RNET_MALLOC(max * sizeof(*set->sockets));
if (set->sockets != NULL)
{
- for (i = 0; i < max; ++i)
- {
- set->sockets[i] = NULL;
- }
+ for (int i = 0; i < max; ++i) set->sockets[i] = NULL;
}
else
{
@@ -1711,6 +1555,7 @@ SocketSet *AllocSocketSet(int max)
set = NULL;
}
}
+
return (set);
}
@@ -1731,58 +1576,55 @@ int AddSocket(SocketSet *set, Socket *sock)
{
if (set->numsockets == set->maxsockets)
{
- TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full");
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", "SocketSet is full");
SocketSetLastError(0);
return (-1);
}
- set->sockets[set->numsockets++] = (struct Socket *) sock;
+ set->sockets[set->numsockets++] = (struct Socket *)sock;
}
else
{
- TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null");
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", "Socket was null");
SocketSetLastError(0);
return (-1);
}
+
return (set->numsockets);
}
// Remove a Socket "sock" to the SocketSet "set"
int RemoveSocket(SocketSet *set, Socket *sock)
{
- int i;
-
if (sock != NULL)
{
+ int i = 0;
for (i = 0; i < set->numsockets; ++i)
{
- if (set->sockets[i] == (struct Socket *) sock)
- {
- break;
- }
+ if (set->sockets[i] == (struct Socket *)sock) break;
}
+
if (i == set->numsockets)
{
- TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found");
+ TRACELOG(LOG_DEBUG, "Socket Error: %s", "Socket not found");
SocketSetLastError(0);
return (-1);
}
+
--set->numsockets;
- for (; i < set->numsockets; ++i)
- {
- set->sockets[i] = set->sockets[i + 1];
- }
+ for (; i < set->numsockets; ++i) set->sockets[i] = set->sockets[i + 1];
}
+
return (set->numsockets);
}
// Check the sockets in the socket set for pending information
int CheckSockets(SocketSet *set, unsigned int timeout)
{
- int i;
- SOCKET maxfd;
- int retval;
+ int i;
+ SOCKET maxfd;
+ int retval;
struct timeval tv;
- fd_set mask;
+ fd_set mask;
/* Find the largest file descriptor */
maxfd = 0;
@@ -1805,7 +1647,8 @@ int CheckSockets(SocketSet *set, unsigned int timeout)
{
FD_SET(set->sockets[i]->channel, &mask);
} // Set up the timeout
- tv.tv_sec = timeout / 1000;
+
+ tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
/* Look! */
@@ -1817,34 +1660,26 @@ int CheckSockets(SocketSet *set, unsigned int timeout)
{
for (i = set->numsockets - 1; i >= 0; --i)
{
- if (FD_ISSET(set->sockets[i]->channel, &mask))
- {
- set->sockets[i]->ready = 1;
- }
+ if (FD_ISSET(set->sockets[i]->channel, &mask)) set->sockets[i]->ready = 1;
}
}
- return (retval);
-}
+
+ return retval;
+}
// Allocate an AddressInformation
AddressInformation AllocAddress()
{
AddressInformation addressInfo = NULL;
addressInfo = (AddressInformation) RNET_CALLOC(1, sizeof(*addressInfo));
+
if (addressInfo != NULL)
{
- addressInfo->addr.ai_addr = (struct sockaddr *) RNET_CALLOC(1, sizeof(struct sockaddr));
- if (addressInfo->addr.ai_addr == NULL)
- {
- TraceLog(LOG_WARNING,
- "Failed to allocate memory for \"struct sockaddr\"");
- }
- }
- else
- {
- TraceLog(LOG_WARNING,
- "Failed to allocate memory for \"struct AddressInformation\"");
+ addressInfo->addr.ai_addr = (struct sockaddr *)RNET_CALLOC(1, sizeof(struct sockaddr));
+ if (addressInfo->addr.ai_addr == NULL) TRACELOG(LOG_WARNING, "Failed to allocate memory for \"struct sockaddr\"");
}
+ else TRACELOG(LOG_WARNING, "Failed to allocate memory for \"struct AddressInformation\"");
+
return addressInfo;
}
@@ -1858,6 +1693,7 @@ void FreeAddress(AddressInformation *addressInfo)
RNET_FREE((*addressInfo)->addr.ai_addr);
(*addressInfo)->addr.ai_addr = NULL;
}
+
RNET_FREE(*addressInfo);
*addressInfo = NULL;
}
@@ -1867,7 +1703,7 @@ void FreeAddress(AddressInformation *addressInfo)
AddressInformation *AllocAddressList(int size)
{
AddressInformation *addr;
- addr = (AddressInformation *) RNET_MALLOC(size * sizeof(AddressInformation));
+ addr = (AddressInformation *)RNET_MALLOC(size * sizeof(AddressInformation));
return addr;
}
@@ -1900,27 +1736,28 @@ char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outp
{
//char *ip[INET6_ADDRSTRLEN];
char *result = NULL;
- struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr;
+ struct sockaddr_storage *storage = (struct sockaddr_storage *)address->addr.ai_addr;
+
switch (storage->ss_family)
{
case AF_INET:
{
- struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr);
+ struct sockaddr_in *s = ((struct sockaddr_in *)address->addr.ai_addr);
//result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); // TODO.
*outport = ntohs(s->sin_port);
- }
- break;
+ } break;
case AF_INET6:
{
- struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr);
+ struct sockaddr_in6 *s = ((struct sockaddr_in6 *)address->addr.ai_addr);
//result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); // TODO.
*outport = ntohs(s->sin6_port);
- }
- break;
+ } break;
+ default: break;
}
+
if (result == NULL)
{
- TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError()));
+ TRACELOG(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError()));
SocketSetLastError(0);
}
else
@@ -1933,39 +1770,40 @@ char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outp
//
void PacketSend(Packet *packet)
{
- printf("Sending packet (%s) with size %d\n", packet->data, packet->size);
+ TRACELOG(LOG_INFO, "Sending packet (%s) with size %d\n", packet->data, packet->size);
}
//
void PacketReceive(Packet *packet)
{
- printf("Receiving packet (%s) with size %d\n", packet->data, packet->size);
+ TRACELOG(LOG_INFO, "Receiving packet (%s) with size %d\n", packet->data, packet->size);
}
//
void PacketWrite16(Packet *packet, uint16_t value)
{
- printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value);
uint8_t *data = packet->data + packet->offs;
- *data++ = (uint8_t)(value >> 8);
- *data++ = (uint8_t)(value);
+ *data++ = (uint8_t)(value >> 8);
+ *data++ = (uint8_t)(value);
packet->size += sizeof(uint16_t);
packet->offs += sizeof(uint16_t);
- printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data);
+ TRACELOG(LOG_INFO, "Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data);
}
//
void PacketWrite32(Packet *packet, uint32_t value)
{
- printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value);
uint8_t *data = packet->data + packet->offs;
- *data++ = (uint8_t)(value >> 24);
- *data++ = (uint8_t)(value >> 16);
- *data++ = (uint8_t)(value >> 8);
- *data++ = (uint8_t)(value);
+ *data++ = (uint8_t)(value >> 24);
+ *data++ = (uint8_t)(value >> 16);
+ *data++ = (uint8_t)(value >> 8);
+ *data++ = (uint8_t)(value);
packet->size += sizeof(uint32_t);
packet->offs += sizeof(uint32_t);
- printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n",
+
+ TRACELOG(LOG_INFO, "Network: 0x%08" PRIX32 " - %" PRIu32 "\n",
(uint32_t)(((intptr_t) packet->data) - packet->offs),
(uint32_t)(((intptr_t) packet->data) - packet->offs));
}
@@ -1973,21 +1811,21 @@ void PacketWrite32(Packet *packet, uint32_t value)
//
void PacketWrite64(Packet *packet, uint64_t value)
{
- printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value);
+
uint8_t *data = packet->data + packet->offs;
- *data++ = (uint8_t)(value >> 56);
- *data++ = (uint8_t)(value >> 48);
- *data++ = (uint8_t)(value >> 40);
- *data++ = (uint8_t)(value >> 32);
- *data++ = (uint8_t)(value >> 24);
- *data++ = (uint8_t)(value >> 16);
- *data++ = (uint8_t)(value >> 8);
- *data++ = (uint8_t)(value);
+ *data++ = (uint8_t)(value >> 56);
+ *data++ = (uint8_t)(value >> 48);
+ *data++ = (uint8_t)(value >> 40);
+ *data++ = (uint8_t)(value >> 32);
+ *data++ = (uint8_t)(value >> 24);
+ *data++ = (uint8_t)(value >> 16);
+ *data++ = (uint8_t)(value >> 8);
+ *data++ = (uint8_t)(value);
packet->size += sizeof(uint64_t);
packet->offs += sizeof(uint64_t);
- printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n",
- (uint64_t)(packet->data - packet->offs),
- (uint64_t)(packet->data - packet->offs));
+
+ TRACELOG(LOG_INFO, "Network: 0x%016" PRIX64 " - %" PRIu64 "\n", (uint64_t)(packet->data - packet->offs), (uint64_t)(packet->data - packet->offs));
}
//
@@ -1997,7 +1835,8 @@ uint16_t PacketRead16(Packet *packet)
packet->size += sizeof(uint16_t);
packet->offs += sizeof(uint16_t);
uint16_t value = ((uint16_t) data[0] << 8) | data[1];
- printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value);
+
return value;
}
@@ -2008,7 +1847,8 @@ uint32_t PacketRead32(Packet *packet)
packet->size += sizeof(uint32_t);
packet->offs += sizeof(uint32_t);
uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3];
- printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value);
+
return value;
}
@@ -2019,6 +1859,7 @@ uint64_t PacketRead64(Packet *packet)
packet->size += sizeof(uint64_t);
packet->offs += sizeof(uint64_t);
uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7];
- printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value);
+ TRACELOG(LOG_INFO, "Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value);
+
return value;
}
diff --git a/src/rnet.h b/src/rnet.h
index 02c2cf1d..03c52cb5 100644
--- a/src/rnet.h
+++ b/src/rnet.h
@@ -2,9 +2,6 @@
*
* rnet - Provides cross-platform network defines, macros etc
*
-* DEPENDENCIES:
-* <limits.h> - Used for cross-platform type specifiers
-*
* INSPIRED BY:
* SFML Sockets - https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Socket.php
* SDL_net - https://www.libsdl.org/projects/SDL_net/
@@ -12,7 +9,6 @@
* BEEJ - https://beej.us/guide/bgnet/html/single/bgnet.html
* Winsock2 - https://docs.microsoft.com/en-us/windows/desktop/api/winsock2
*
-*
* CONTRIBUTORS:
* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version
*
@@ -135,14 +131,14 @@ typedef int socklen_t;
//----------------------------------------------------------------------------------
// Include system network headers
-#if defined(_WIN32)
+#if defined(_WIN32) // Windows
#define __USE_W32_SOCKETS
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <io.h>
#define IPTOS_LOWDELAY 0x10
-#else // Unix
+#else // Unix
#include <sys/types.h>
#include <fcntl.h>
#include <netinet/in.h>
@@ -178,27 +174,34 @@ typedef int socklen_t;
//----------------------------------------------------------------------------------
// Network connection related defines
-#define SOCKET_MAX_SET_SIZE (32) // Maximum sockets in a set
-#define SOCKET_MAX_QUEUE_SIZE (16) // Maximum socket queue size
-#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options
-#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels
-#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses
-
+#define SOCKET_MAX_SET_SIZE 32 // Maximum sockets in a set
+#define SOCKET_MAX_QUEUE_SIZE 16 // Maximum socket queue size
+#define SOCKET_MAX_SOCK_OPTS 4 // Maximum socket options
+#define SOCKET_MAX_UDPCHANNELS 32 // Maximum UDP channels
+#define SOCKET_MAX_UDPADDRESSES 4 // Maximum bound UDP addresses
// Network address related defines
-#define ADDRESS_IPV4_ADDRSTRLEN (22) // IPv4 string length
-#define ADDRESS_IPV6_ADDRSTRLEN (65) // IPv6 string length
-#define ADDRESS_TYPE_ANY (0) // AF_UNSPEC
-#define ADDRESS_TYPE_IPV4 (2) // AF_INET
-#define ADDRESS_TYPE_IPV6 (23) // AF_INET6
-#define ADDRESS_MAXHOST (1025) // Max size of a fully-qualified domain name
-#define ADDRESS_MAXSERV (32) // Max size of a service name
+#define ADDRESS_IPV4_ADDRSTRLEN 22 // IPv4 string length
+#define ADDRESS_IPV6_ADDRSTRLEN 65 // IPv6 string length
+#define ADDRESS_TYPE_ANY 0 // AF_UNSPEC
+#define ADDRESS_TYPE_IPV4 2 // AF_INET
+#define ADDRESS_TYPE_IPV6 23 // AF_INET6
+#define ADDRESS_MAXHOST 1025 // Max size of a fully-qualified domain name
+#define ADDRESS_MAXSERV 32 // Max size of a service name
// Network address related defines
-#define ADDRESS_ANY ((unsigned long) 0x00000000)
-#define ADDRESS_LOOPBACK (0x7f000001)
-#define ADDRESS_BROADCAST ((unsigned long) 0xffffffff)
-#define ADDRESS_NONE (0xffffffff)
+#define ADDRESS_ANY (unsigned long)0x00000000
+#define ADDRESS_LOOPBACK 0x7f000001
+#define ADDRESS_BROADCAST (unsigned long)0xffffffff
+#define ADDRESS_NONE xffffffff
+
+// Network resolution related defines
+#define NAME_INFO_DEFAULT 0x00 // No flags set
+#define NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts
+#define NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address
+#define NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS
+#define NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #)
+#define NAME_INFO_DGRAM 0x10 // Service is a datagram service
// Address resolution related defines
#if defined(_WIN32)
@@ -220,14 +223,6 @@ typedef int socklen_t;
#define ADDRESS_INFO_RESOLUTION_HANDLE (0x40000000) // Request resolution handle
#endif
-// Network resolution related defines
-#define NAME_INFO_DEFAULT (0x00) // No flags set
-#define NAME_INFO_NOFQDN (0x01) // Only return nodename portion for local hosts
-#define NAME_INFO_NUMERICHOST (0x02) // Return numeric form of the host's address
-#define NAME_INFO_NAMEREQD (0x04) // Error if the host's name not in DNS
-#define NAME_INFO_NUMERICSERV (0x08) // Return numeric form of the service (port #)
-#define NAME_INFO_DGRAM (0x10) // Service is a datagram service
-
//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
@@ -239,6 +234,11 @@ typedef int socklen_t;
typedef enum { false, true } bool;
#endif
+typedef enum {
+ SOCKET_TCP = 0, // SOCK_STREAM
+ SOCKET_UDP = 1 // SOCK_DGRAM
+} SocketType;
+
// Network typedefs
typedef uint32_t SocketChannel;
typedef struct _AddressInformation *AddressInformation;
@@ -249,83 +249,78 @@ typedef struct _SocketAddressStorage *SocketAddressStorage;
// IPAddress definition (in network byte order)
typedef struct IPAddress {
- unsigned long host; /* 32-bit IPv4 host address */
- unsigned short port; /* 16-bit protocol port */
+ unsigned long host; // 32-bit IPv4 host address
+ unsigned short port; // 16-bit protocol port
} IPAddress;
// An option ID, value, sizeof(value) tuple for setsockopt(2).
typedef struct SocketOpt {
- int id;
- void *value;
- int valueLen;
+ int id; // Socked option id
+ int valueLen; // Socked option value len
+ void *value; // Socked option value data
} SocketOpt;
-typedef enum {
- SOCKET_TCP = 0, // SOCK_STREAM
- SOCKET_UDP = 1 // SOCK_DGRAM
-} SocketType;
-
typedef struct UDPChannel {
- int numbound; // The total number of addresses this channel is bound to
+ int numbound; // The total number of addresses this channel is bound to
IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to
} UDPChannel;
typedef struct Socket {
- int ready; // Is the socket ready? i.e. has information
- int status; // The last status code to have occured using this socket
- bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server)
- SocketChannel channel; // The socket handle id
- SocketType type; // Is this socket a TCP or UDP socket?
- bool isIPv6; // Is this socket address an ipv6 address?
+ int ready; // Is the socket ready? i.e. has information
+ int status; // The last status code to have occured using this socket
+ bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server)
+ SocketChannel channel; // The socket handle id
+ SocketType type; // Is this socket a TCP or UDP socket?
+ bool isIPv6; // Is this socket address an ipv6 address?
SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order)
SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order)
struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to
} Socket;
+// Result from calling open with a given config
+typedef struct SocketResult {
+ int status; // Socket result state
+ Socket *socket; // Socket ref
+} SocketResult;
+
typedef struct SocketSet {
- int numsockets;
- int maxsockets;
- struct Socket **sockets;
+ int numsockets; // Socket set count
+ int maxsockets; // Socket set max
+ struct Socket **sockets; // Sockets array
} SocketSet;
typedef struct SocketDataPacket {
- int channel; // The src/dst channel of the packet
- unsigned char *data; // The packet data
- int len; // The length of the packet data
- int maxlen; // The size of the data buffer
- int status; // packet status after sending
- IPAddress address; // The source/dest address of an incoming/outgoing packet
+ IPAddress address; // The source/dest address of an incoming/outgoing packet
+ int channel; // The src/dst channel of the packet
+ int maxlen; // The size of the data buffer
+ int status; // Packet status after sending
+ unsigned int len; // The length of the packet data
+ unsigned char *data; // The packet data
} SocketDataPacket;
-// Configuration for a socket.
+// Configuration for a socket
typedef struct SocketConfig {
- char * host; // The host address in xxx.xxx.xxx.xxx form
- char * port; // The target port/service in the form "http" or "25565"
- bool server; // Listen for incoming clients?
- SocketType type; // The type of socket, TCP/UDP
- bool nonblocking; // non-blocking operation?
- int backlog_size; // set a custom backlog size
- SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS];
+ SocketType type; // The type of socket, TCP/UDP
+ char *host; // The host address in xxx.xxx.xxx.xxx form
+ char *port; // The target port/service in the form "http" or "25565"
+ bool server; // Listen for incoming clients?
+ bool nonblocking; // non-blocking operation?
+ int backlog_size; // set a custom backlog size
+ SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS];
} SocketConfig;
-// Result from calling open with a given config.
-typedef struct SocketResult {
- int status;
- Socket *socket;
-} SocketResult;
-
// Packet type
typedef struct Packet {
- uint32_t size; // The total size of bytes in data
- uint32_t offs; // The offset to data access
- uint32_t maxs; // The max size of data
- uint8_t *data; // Data stored in network byte order
+ uint32_t size; // The total size of bytes in data
+ uint32_t offs; // The offset to data access
+ uint32_t maxs; // The max size of data
+ uint8_t *data; // Data stored in network byte order
} Packet;
#ifdef __cplusplus
-extern "C" { // Prevents name mangling of functions
+extern "C" { // Prevents name mangling of functions
#endif
//----------------------------------------------------------------------------------