// Cross-Platform Sockets Library - by dark2k1(dark2k1.com)
// I often make references to this library in some of my code(socket.h)
#include <iostream>
// Windows - 1
// Unix - 2
#define OS 1
#define MTU 1500
#if OS == 1
#include <winsock.h>
#elif OS == 2
#include <sys/socket.h>
#include <netdb.h>
#endif
int close(void);
class SOCK {
public:
int sockfd;
void socket(int family, int type, int protocol) {
#if OS == 1
WSADATA wsaData;
WORD version;
version = MAKEWORD(2, 0);
WSAStartup(version, &wsaData);
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0 ) {
WSACleanup();
}
this->sockfd = WSASocket(family, type, protocol, NULL, 0, 0);
if(this->sockfd == INVALID_SOCKET) {
perror("WSASocket");
}
#elif OS == 2
this->sockfd = socket(family, type, protocol);
if(this->sockfd < 0) {
perror("socket");
}
#endif
}
int connect(char host[], int port) {
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr(host);
#if OS == 1
if(WSAConnect(sockfd, (struct sockaddr *)&sin, sizeof(sin), NULL, 0, 0, 0) != 0) {
return -1;
} else {
return 1;
}
#elif OS == 2
if(connect(sockfd, (struct sockaddr_in *)&sin, sizeof(sin)) < 0) {
return -1;
} else {
return 1;
}
#endif
}
int write(char buffer[]) {
int length;
length = strlen(buffer);
if(send(this->sockfd, buffer, length, 0) < 0) {
return -1;
} else {
return 1;
}
}
int read(char *buffer) {
int length = 0;
length = recv(this->sockfd, buffer, MTU, 0);
return length;
}
int close() {
#if OS == 1
int ret;
ret = shutdown(this->sockfd, 2);
WSACleanup();
#elif OS == 2
int ret;
ret = close(this->sockfd);
#endif
return ret;
}
};