#include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #define MAXLINE 4096 int daemon_init(const char *, int); int tcp_listen(const char *, const char *, socklen_t *); char *sock_ntop(const struct sockaddr *, socklen_t); void err_msg(const char *, ...); void err_quit(const char *, ...); int main(int argc, char **argv) { int listenfd, connfd; socklen_t addrlen, len; struct sockaddr *cliaddr; char buff[MAXLINE]; time_t ticks; if (argc < 2 || argc > 3) { err_quit("usage: %s [ <host> ] <service or port>", argv[0]); } daemon_init(argv[0], 0); if (argc == 2) { listenfd = tcp_listen(NULL, argv[1], &addrlen); } else { listenfd = tcp_listen(argv[1], argv[2], &addrlen); } cliaddr = malloc(addrlen); for ( ; ; ) { len = addrlen; connfd = accept(listenfd, cliaddr, &len); err_msg("connection from %s", sock_ntop(cliaddr, len)); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); write(connfd, buff, strlen(buff)); close(connfd); } }
原文地址:https://www.cnblogs.com/soldierback/p/10755650.html
时间: 2024-10-22 20:19:39