@zwh8800
2017-08-23T10:23:38.000000Z
字数 938
阅读 191076
blog
归档
网络编程
tcp/ip
例子
时间服务器小例子
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
using namespace std;
int main()
{
int serverSock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddr;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(13);
bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
listen(serverSock, 5);
while (true)
{
struct sockaddr_in clientAddr;
socklen_t len = sizeof(clientAddr);
int clientSock = accept(serverSock, (struct sockaddr*)&clientAddr, &len);
char ipbuf[INET_ADDRSTRLEN];
printf("connection from %s, port %d\n",
inet_ntop(AF_INET, &clientAddr.sin_addr, ipbuf, sizeof(ipbuf)),
ntohs(clientAddr.sin_port));
time_t t = time(NULL);
char buf[1024];
snprintf(buf, 1024, "%.24s\r\n", ctime(&t));
write(clientSock, buf, strlen(buf));
close(clientSock);
}
return 0;
}
抄书copy了一下