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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <ctype.h> #include <unistd.h> #include <errno.h> #include <sys/socket.h>
#define BUF_SIZE 1024
void error_handling(char *message);
int main(int argc, char *argv[]) { if (argc != 2) { printf("Invalid port,please check out port"); exit(1); }
int server_sockfd, client_sockfd; int server_len, client_len; int fd_max, n; char buf[BUF_SIZE], str[INET_ADDRSTRLEN]; struct sockaddr_in server_address; struct sockaddr_in client_address; int result; fd_set readfds, tempfds; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(atoi(argv[1])); server_len = sizeof(server_address); if (bind(server_sockfd, (struct sockaddr *)&server_address, server_len) == -1) { error_handling("bind error"); }
if (listen(server_sockfd, 128) == -1) { error_handling("listen error"); }
printf("server waiting\n"); FD_ZERO(&readfds); FD_SET(server_sockfd, &readfds); fd_max = server_sockfd;
struct timeval timeout; while (1) { tempfds = readfds; timeout.tv_sec = 3; timeout.tv_usec = 0; result = select(fd_max + 1, &tempfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0); printf("-------next--------\n"); if (result < 0) { error_handling("select error"); break; }
for (size_t fd = 0; fd < fd_max + 1; fd++) { if (FD_ISSET(fd, &tempfds)) { if (fd == server_sockfd) { client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); printf("received from %s at PORT %d on fd %d\n", inet_ntop(AF_INET, &client_address.sin_addr, str, sizeof(str)), ntohs(client_address.sin_port), client_sockfd); FD_SET(client_sockfd, &readfds); if (fd_max < client_sockfd) fd_max = client_sockfd; } else { if ((n = read(fd, buf, sizeof(buf))) == 0) { close(fd); FD_CLR(fd, &readfds); } else if (n > 0) {
for (size_t j = 0; j < n; j++) buf[j] = toupper(buf[j]); write(fd, buf, n); write(STDOUT_FILENO, buf, n); } } } } } close(server_sockfd); printf("--------------------server finish!"); }
void error_handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
|