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
| #include <asm-generic/socket.h> #include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h> #include <string.h> #include <unistd.h>
int main(){ int socketfd, clientfd; struct sockaddr_in address, client_address; int addrlen; char buffer[1024] = {0};
printf("current pid=%d\n", getpid());
socketfd = socket(AF_INET,SOCK_STREAM,0); if(socketfd == 0){ perror("socket created failed\n"); exit(-1); }
int optval = 1; if(setsockopt(socketfd, SOL_SOCKET, SO_REUSEPORT, (const void*)&optval, sizeof(optval))){ perror("setsocketopt failed\n"); exit(-1); }
address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(8989); if(bind(socketfd, (const struct sockaddr*)&address,sizeof(address)) < 0){ perror("socket created failed\n"); exit(-1); }
if(listen(socketfd, 511) < 0){ perror("listen error"); exit(-1); } printf("start listening\n"); while(1){ clientfd = accept(socketfd, (struct sockaddr *)&client_address, (socklen_t*)&addrlen); if(clientfd < 0){ perror("accept failed\n"); exit(-1); } printf("accept client=%d\n", clientfd); memset(buffer, 0, 1024); int n = read(clientfd, buffer, 1024); if(n == 0){ printf("client:%d close the socket\n",clientfd); close(clientfd); continue; } printf("read from client : %s\n", buffer); write(clientfd, buffer, n); close(clientfd); }
return 0; }
|