From ce4de7865678c445f4c88701b57bf1c580e12201 Mon Sep 17 00:00:00 2001 From: xotnet <150250186+xotnet@users.noreply.github.com> Date: Mon, 25 Mar 2024 01:10:36 +0530 Subject: [PATCH] Add files via upload --- net.hpp | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 net.hpp diff --git a/net.hpp b/net.hpp new file mode 100644 index 0000000..7d65982 --- /dev/null +++ b/net.hpp @@ -0,0 +1,71 @@ +#ifdef __WIN32 + #include +#else + #include + #include +#endif +#include +#include +int listen_net(const char* port) { + #ifdef __WIN32 + WSADATA wsa; + WSAStartup(MAKEWORD(2,2), &wsa); + #endif + int listener = socket(AF_INET, SOCK_STREAM, 0); + const int enable = 1; + setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(int)); + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(atoi(port)); + addr.sin_addr.s_addr = INADDR_ANY; + bind(listener, reinterpret_cast(&addr), sizeof(addr)); + listen(listener, SOMAXCONN); + return listener; +} + +int accept_net(int listener) { + return accept(listener, 0, 0); +} + +int connect_net(const char* ip, const char* port) { + #ifdef __WIN32 + WSADATA wsa; + WSAStartup(MAKEWORD(2,2), &wsa); + #endif + int conn = socket(AF_INET, SOCK_STREAM, 0); + const int enable = 1; + setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(int)); + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(atoi(port)); + addr.sin_addr.s_addr = inet_addr(ip); + connect(conn, reinterpret_cast(&addr), sizeof(addr)); + return conn; +} + +int send_net(int socket, char* buf, size_t size) { + return send(socket, buf, (int)size, 0); +} + +int recv_net(int socket, char* buf, int size) { + return recv(socket, buf, size, 0); +} + +char* resolve_net(const char* domain) { + #ifdef __WIN32 + WSADATA wsaData; + int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); + #endif + struct hostent* remoteHost = gethostbyname(domain); + struct in_addr addr; + memcpy(&addr, remoteHost->h_addr_list[0], sizeof(struct in_addr)); + return inet_ntoa(addr); +} + +int close_net(int conn) { + #ifdef __WIN32 + return closesocket(conn); + #elif __linux__ + return close(conn); + #endif +} \ No newline at end of file