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
|
#include "single_socket.h" int main(int argc, char **argv){
int listenfd, connfd; char buff[30]; listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); init_serv_addr(&serv_addr); bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); listen(listenfd, BACK_LOG); struct sockaddr_in cli_addr; socklen_t addrlen = sizeof(cli_addr); for(; ;){ errno = 0; connfd = accept(listenfd,(struct sockaddr*)&cli_addr, &addrlen); if(connfd <= 0){ printf("[Server] connection error : %d",errno); break; } printf("[Server] connection from %s port: %d\n", inet_ntop(AF_INET, &cli_addr.sin_addr,buff, sizeof(buff)),ntohs(cli_addr.sin_port)); char str[] = "hello world!\n"; write(connfd,str, sizeof(str)); if(errno != 0){ printf("[Server] connect error: %d\n", errno); } close(connfd); } close(listenfd); printf("[Server] connect close: %d\n", getpid()); return 0; }
|