daytime服务器与客户端(程序)
这个程序有几处错误,其实是很简单的错误,过些日子我在把正确的发上来。
在linux下编译运行。
服务器:
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_LINE 256
int main(int argc, char** argv)
{
int listenfd, connfd;
struct sockaddr_in servadd;
char buff[MAX_LINE];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servadd, sizeof(servadd));
servadd.sin_family = AF_INET;
servadd.sin_addr.s_addr = htonl(INADDR_ANY);
servadd.sin_port = htons(13);
bind(listenfd, (struct sockaddr*)&servadd, sizeof(servadd));
listen(listenfd, 0);
for(; ;)
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
write(connfd, buff, strlen(buff));
close(connfd);
}
}
客户端
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAXLINE 256
int main(int argc, char** argv)
{
int socketfd, n;
char recvline[MAXLINE+1];
struct sockaddr_in servaddr;
if(argc != 2)
{
printf("usage:a.out<IP address>\n");
exit(-1);
}
if((socketfd=socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket err\n");
exit(-1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
{
printf("inet_pton error for %s\n", argv[1]);
exit(-1);
}
if(connect(socketfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
{
printf("connect error\n");
exit(-1);
}
while((n=read(socketfd, recvline, MAXLINE))>0)
{
recvline[n] = 0;
if(fputs(recvline, stdout) == EOF)
{
printf("fputs error\n");
exit(-1);
}
}
if(n<0)
{
printf("read error\n");
exit(-1);
}
exit(0);
}