获取时间服务服务端
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#define MAXLINE 4096
#define LISTENQ 1024
typedef struct sockaddr SA;
int main(int argc, char *argv[]) {
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9999);
bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
listen(listenfd, LISTENQ);
while (true) {
connfd = accept(listenfd, (SA *)NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
write(connfd, buff, strlen(buff));
std::cout << buff << std::endl;
close(connfd);
}
return 0;
}
客户端
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
const int MAXLINE=4096;
typedef sockaddr SA;
int main(int argc, char ** argv) {
int sockfd , n;
char recvline[MAXLINE +1];
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
std::cout << "socket error" <<std::endl;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
//
servaddr.sin_port = htons(9999);
if( inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <= 0){
std::cout << "inet_pton error for " << argv[1] << std::endl;
}
if(connect(sockfd,(sockaddr *)&servaddr, sizeof(servaddr)) < 0){
std::cout << "connet error" <<std::endl;
}
while ((n = read(sockfd,recvline, MAXLINE)) > 0){
recvline[n] = 0;
if(fputs(recvline, stdout) == EOF)
std::cout <<"Fputs error" << std::endl;
}
if (n < 0){
std::cout << "read error" <<std::endl;
}
return 0;
}