
CS485G Spring 2015 51
11. Sample server for ”echo”
1 int server(int argc, char
**
argv) {
2 int listenfd, connfd, listenPort;
3 struct sockaddr_in clientAddr;
4 struct hostent
*
clientHostEntry;
5 char
*
clientIP;
6 unsigned short clientPort;
7 listenPort = atoi(argv[1]);
8 listenfd = open_listenfd(listenPort);
9 while (1) {
10 socklen_t addrLength = sizeof(clientAddr);
11 connfd = Accept(listenfd, (SA
*
)&clientAddr, &addrLength);
12 if (connfd < 1) perror("accept error");
13 // the following is optional to get info on the client
14 clientHostEntry = Gethostbyaddr(
15 (const char
*
)&clientAddr.sin_addr.s_addr,
16 sizeof(clientAddr.sin_addr.s_addr),
17 AF_INET);
18 clientIP = inet_ntoa(clientAddr.sin_addr);
19 // net-to-ASCII string in dotted notation
20 clientPort = ntohs(clientAddr.sin_port);
21 printf("server connected to %s (%s) on my new clientPort %u\n",
22 clientHostEntry->h_name, clientIP, clientPort);
23 // end of optional part
24 echo(connfd);
25 Close(connfd);
26 } // while(1)
27 } // server
Comentarios a estos manuales