bcssocket/client.c

59 lines
1.8 KiB
C

// 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/client.h"
void setSockAddress(int argc, char *argv[], struct sockaddr_in * address);
int main(int argc, char *argv[]) {
int fd;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printSystemError("User: socket()");
struct sockaddr_in serv_addr;
setSockAddress(argc, argv, &serv_addr);
if (connect(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
printSystemError("User: connect()");
char input[MAX_LEN] = {0};
int readChars;
while ((readChars = read(STDIN_FILENO, input, MAX_LEN - 1)) != 0) {
if (readChars < 0)
printSystemError("User: read()");
input[readChars] = '\0';
if (write(fd, input, readChars) < 0)
printSystemError("User: write()");
}
close(fd);
return EXIT_SUCCESS;
}
void setSockAddress(int argc, char *argv[], struct sockaddr_in * address) {
address->sin_family = AF_INET;
if (argc == 1) {
address->sin_addr.s_addr = inet_addr(ADDRESS);
address->sin_port = htons(PORT);
}
int opt;
while ((opt = getopt(argc, argv, "a:p:")) != -1) {
switch (opt) {
case 'a':
if (optarg[0] == '-')
printError("Usage: server [-a address] [-p port]\n");
address->sin_addr.s_addr = inet_addr(optarg);
break;
case 'p':
if (optarg[0] == '-')
printError("Usage: server [-a address] [-p port]\n");
address->sin_port = htons(atoi(optarg));
break;
default:
printError("Usage: server [-a address] [-p port]\n");
}
}
}