From f9d5e8cdeb3d3e384975bf725419cbec78a0b534 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Sat, 9 Mar 2024 11:02:50 -0500 Subject: [PATCH] Converted easysock from CPP to C, because it was mostly just C code anyways --- easysock.cpp => easysock.c | 34 +++++++++++++++++++++++---- includes/{easysock.hpp => easysock.h} | 16 +++++++++++-- 2 files changed, 43 insertions(+), 7 deletions(-) rename easysock.cpp => easysock.c (88%) rename includes/{easysock.hpp => easysock.h} (87%) diff --git a/easysock.cpp b/easysock.c similarity index 88% rename from easysock.cpp rename to easysock.c index 195f7ad..cc4cea4 100644 --- a/easysock.cpp +++ b/easysock.c @@ -1,8 +1,9 @@ -#include "includes/easysock.hpp" -#include -#include -#include -#include +#include "includes/easysock.h" +#include +#include +#include +#include +#include #include #ifndef _WIN32 @@ -187,6 +188,29 @@ int check_ip_ver(const char* address) { } } +int port_to_num(const char* port_str) { + /* The largest possible port value is 65535: a 5 character string */ + if (strlen(port_str) > 5) { + return -1; + } + + for (int i = 0; i < strlen(port_str); i++) { + if (isdigit(port_str[i]) == 0) { // Ensure that every character in port_str is a digit (isidigit() returns 0 if the parameter is not a digit) + return -1; + } + } + /* Convert the string to a base-10 integer */ + int port_num = (int)strtol(port_str, NULL, 10); + if (port_num > 65535) { + return -1; + } + if (port_num < 1024) { + return -2; + } + + return port_num; +} + int int_to_inet(int network) { if (network == 4) { return AF_INET; diff --git a/includes/easysock.hpp b/includes/easysock.h similarity index 87% rename from includes/easysock.hpp rename to includes/easysock.h index f374278..0348838 100644 --- a/includes/easysock.hpp +++ b/includes/easysock.h @@ -1,5 +1,8 @@ -#ifndef EASYSOCK_HPP_ -#define EASYSOCK_HPP_ +#ifdef __cplusplus +extern "C" { +#endif +#ifndef EASYSOCK_H_ +#define EASYSOCK_H_ #ifdef _WIN32 #include @@ -70,6 +73,12 @@ IPv6 address (returns 6) or neither (returns -1). */ int check_ip_ver(const char* address); +/* port_to_num - Converts a string representing a port, into a numeric value. +Returns -1 if the string is not numeric, or exceeds the maximum port length. +Returns -2 if the string is lower than 1024, This serves as a warning, as ports less +than 1023 are reserved. */ +int port_to_num(const char* port_str); + /* int_to_inet - Takes an int value (4 for IPv4, 6 for IPv6) and returns AF_INET or AF_INET6 respectively. */ @@ -92,3 +101,6 @@ int sock_quit(void); int sock_close(SOCKET); #endif +#ifdef __cplusplus +} +#endif