1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <errno.h> #include <string.h>
#define MAX_CONNECTION_QUEUE_SIZE 50 #define MAX_BUFF_SIZE 255
extern int errno;
int createServer(in_port_t port); void startServer(int socket);
int main(int argc, char **argv) { if (argc != 2) { printf("[%s](%s:%d) - Usage: ./a.out <port>\n", __FILE__, __FUNCTION__, __LINE__); exit(0); } int port = atoi(argv[1]); int fd = createServer(port); if (fd == -1) { exit(0); } startServer(fd); return 0; }
int createServer(in_port_t port) { int serverfd = socket(PF_INET, SOCK_STREAM, NULL); if (serverfd == -1) { printf("[%s](%s:%d) - socket create error code %s\n", __FILE__, __FUNCTION__, __LINE__, strerror(errno)); return -1; }
struct sockaddr_in address; address.sin_family = PF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port);
if (bind(serverfd, (struct sockaddr *)&address, sizeof(address)) == -1) { printf("[%s](%s:%d) - address bind error code %s\n", __FILE__, __FUNCTION__, __LINE__, strerror(errno)); return -1; }
if (listen(serverfd, MAX_CONNECTION_QUEUE_SIZE) == -1) { printf("[%s](%s:%d) - socket listen error code %s\n", __FILE__, __FUNCTION__, __LINE__, strerror(errno)); return -1; }
return serverfd; }
void startServer(int socket) { while (1) { struct sockaddr_in address; int address_len = sizeof(address); int connection = accept(socket, &address, &address_len); if (connection == -1) { printf("[%s](%s:%d) - connection error code %s\n", __FILE__, __FUNCTION__, __LINE__, strerror(errno)); } else { char buf[MAX_BUFF_SIZE] = ""; ssize_t len = recv(connection, buf, sizeof(buf), 0); buf[len] = '\0'; printf("[%s](%s:%d) - message: %s\n", __FILE__, __FUNCTION__, __LINE__, buf); send(connection, buf, sizeof(buf), 0); } } }
|