#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXSOCKETLEN 1024
static void err_doit(int errnoflag, const char *fmt, va_list ap)
{
char buf[1024];
vsprintf(buf, fmt, ap);
if (errnoflag)
{
if (errno >= 0 && errno <= sys_nerr)
{
sprintf(buf+strlen(buf), ": %s", strerror(errno));
}
}
strcat(buf, "
");
fflush(stdout);
fputs(buf, stderr);
fflush(stderr);
}
void err_print(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1, fmt, ap);
va_end(ap);
exit(1);
}
int main()
{
int sockfd = 0;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
err_print("socket fd created failed");
}
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(43521);
if (bind(sockfd, (struct sockaddr *)(&servaddr), sizeof(servaddr)) < 0)
{
err_print("bind failed");
}
if (listen(sockfd, MAXSOCKETLEN) < 0)
{
err_print("listen failed");
}
while (1)
{
char buff[1024];
memset(buff, 0,sizeof(buff));
int connfd = -1;
connfd = accept(sockfd, (struct sockaddr *)NULL, NULL);
if (connfd < 0)
{
err_print("accept failed");
}
time_t ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s", ctime(&ticks));
size_t size = send(connfd, buff, strlen(buff), 0);
printf("send size:%d, message:%s
", (int)size, buff);
if (size < 0)
{
err_print("write failed");
}
close(connfd);
};
return 0;
}