#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <signal.h>
#define PORT 6666 #define LISTEN_QUEUE 200
#define errexit(msg) do{perror(msg); exit(EXIT_FAILURE);} while (0)
int main(int argc, char *argv[]) { int listenfd, clt_fd; int on = 1; pid_t pid;
struct sockaddr_in srv_addr, clt_addr; int addrlen;
int len; char recvbuf[1024]; /* you'd better use malloc function to allocate memory for it */
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) errexit("socket error");
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) perror("warning: setsockopt reuse addr failed!");
addrlen = sizeof(struct sockaddr); memset(&srv_addr, 0, addrlen); srv_addr.sin_family = AF_INET; srv_addr.sin_port = htons(PORT); srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listenfd, (struct sockaddr *)&srv_addr, addrlen) < 0) { close(listenfd); errexit("bind error"); }
if (listen(listenfd, LISTEN_QUEUE) < 0) { close(listenfd); errexit("listen error"); }
signal(SIGCHLD, SIG_IGN);
printf("waiting for accepting connection...\n"); while (1) { clt_fd = accept(listenfd, (struct sockaddr *)&clt_addr, &addrlen); if (clt_fd < 0) { if (errno == EINTR) continue; else { perror("cannot accept client connect request!"); close(listenfd); exit(1); } }
if ((pid = fork()) < 0) { perror("fork error"); close(listenfd); close(clt_fd); exit(1); } else if (pid == 0) { memset(recvbuf, 0, sizeof(recvbuf)); while ((len = recv(clt_fd, recvbuf, sizeof(recvbuf), 0)) > 0) { printf("Message from client(%d): %s\n", len, recvbuf); if (recvbuf[0] == '@') break; int i; for (i=0; i<len; i++) recvbuf[i] = toupper(recvbuf[i]); send(clt_fd, recvbuf, sizeof(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); } close(clt_fd); close(listenfd); _exit(0); } else { close(clt_fd); } }
exit(0); }
|