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
| #include <iostream> #include <time.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <cstring> #include <cstdio> #include <cstdlib>
#define MAXLINE 4096 #define LISTENQ 1024
using namespace std;
int main(int argc, char **argv){ int listenfd, connfd; struct sockaddr_in servaddr; char buff[MAXLINE]; time_t ticks;
if (argc != 2){ cerr << "usage: " << argv[0] << " <listen_port>" << endl; return 0; } if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ){ cerr << "socket error" << endl; return 0; }
bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(atoi(argv[1])); if ( bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ){ cerr << "bind error" << endl; return 0; }
if (listen(listenfd, LISTENQ) < 0){ cerr << "listen error" << endl; return 0; }
for (;;){ if ((connfd = accept(listenfd, (struct sockaddr *) NULL, NULL)) < 0){ cerr << "accept error" << endl; return 0; } ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); if ( write(connfd, buff, strlen(buff)) < 0 ){ cerr << "write error" << endl; return 0; }
if (close(connfd) < 0){ cerr << "close error" << endl; return 0; } }
return 0; }
|