// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "include/sockets.h" int createSocket() { int fd; if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) printSystemError("Sockets: socket()"); return fd; } void setSockOptions(int fd) { int opt = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) printSystemError("Sockets: setsockopt()"); } int bindAndGetSocket(int fd, struct sockaddr_in *address) { if (bind(fd, (struct sockaddr *) address, sizeof(*address)) < 0) printSystemError("Sockets: bind()"); if (listen(fd, MAX_PEND_REQ) < 0) printSystemError("Sockets: listen()"); int addrlen = sizeof(*address), fdAux; if ((fdAux = accept(fd, (struct sockaddr *) address, (socklen_t *) &addrlen)) < 0) printSystemError("Sockets: accept()"); return fdAux; } void connectToSocket(int fd, struct sockaddr_in *address) { if (connect(fd, (struct sockaddr *) address, sizeof(*address)) < 0) printSystemError("Sockets: connect()"); } void closeSocket(int fd) { if (close(fd) < 0) printSystemError("Sockets: close()"); } void setSockAddress(int argc, char *argv[], struct sockaddr_in * address, in_addr_t inAddress) { address->sin_family = AF_INET; address->sin_addr.s_addr = htonl(inAddress); address->sin_port = htons(PORT); int opt; opterr = 0; while ((opt = getopt(argc, argv, "a:p:")) != -1) { if (optarg[0] == '-') printError("Usage: server [-a address] [-p port]\n"); switch (opt) { case 'a': if (inet_pton(AF_INET, optarg, &address->sin_addr) <= 0) printError("Sockets: inet_pton()"); break; case 'p': address->sin_port = htons(atoi(optarg)); break; default: printError("Usage: server [-a address] [-p port]\n"); } } }