TCP 日間迭代伺服器
這是一個儘可能簡單的 TCP 日間迭代伺服器。
#include <sys/types.h> /* predefined types */
#include <unistd.h> /* unix standard library */
#include <arpa/inet.h> /* IP addresses conversion utilities */
#include <netinet/in.h> /* sockaddr_in structure definition */
#include <sys/socket.h> /* berkley socket library */
#include <stdio.h> /* standard I/O library */
#include <string.h> /* include to have memset */
#include <stdlib.h> /* include to have exit */
#include <time.h> /* time manipulation primitives */
#define MAXLINE 80
#define BACKLOG 10
int main(int argc, char *argv[])
{
int list_fd, conn_fd;
struct sockaddr_in serv_add;
char buffer[MAXLINE];
time_t timeval;
/* socket creation third parameter should be IPPROTO_TCP but 0 is an
* accepted value */
list_fd = socket(AF_INET, SOCK_STREAM, 0);
/* address initialization */
memset(&serv_add, 0, sizeof(serv_add)); /* init the server address */
serv_add.sin_family = AF_INET; /* address type is IPV4 */
serv_add.sin_port = htons(13); /* daytime port is 13 */
serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
/* bind socket */
bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add));
/* listen on socket */
listen(list_fd, BACKLOG);
while (1)
{
/* accept connection */
conn_fd = accept(list_fd, (struct sockaddr *) NULL, NULL);
timeval = time(NULL);
snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
write(conn_fd, buffer, strlen(buffer)); /* write daytime to client */
close(conn_fd);
}
/* normal exit */
close(list_fd);
exit(0);
}