[关闭]
@zwh8800 2017-08-23T02:23:38.000000Z 字数 938 阅读 190187

时间服务器小例子

blog 归档 网络编程 tcp/ip 例子


时间服务器小例子


  1. #include <netinet/in.h>
  2. #include <arpa/inet.h>
  3. #include <sys/socket.h>
  4. #include <unistd.h>
  5. #include <stdio.h>
  6. #include <time.h>
  7. #include <string.h>
  8. using namespace std;
  9. int main()
  10. {
  11. int serverSock = socket(AF_INET, SOCK_STREAM, 0);
  12. struct sockaddr_in serverAddr;
  13. bzero(&serverAddr, sizeof(struct sockaddr_in));
  14. serverAddr.sin_family = AF_INET;
  15. serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  16. serverAddr.sin_port = htons(13);
  17. bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
  18. listen(serverSock, 5);
  19. while (true)
  20. {
  21. struct sockaddr_in clientAddr;
  22. socklen_t len = sizeof(clientAddr);
  23. int clientSock = accept(serverSock, (struct sockaddr*)&clientAddr, &len);
  24. char ipbuf[INET_ADDRSTRLEN];
  25. printf("connection from %s, port %d\n",
  26. inet_ntop(AF_INET, &clientAddr.sin_addr, ipbuf, sizeof(ipbuf)),
  27. ntohs(clientAddr.sin_port));
  28. time_t t = time(NULL);
  29. char buf[1024];
  30. snprintf(buf, 1024, "%.24s\r\n", ctime(&t));
  31. write(clientSock, buf, strlen(buf));
  32. close(clientSock);
  33. }
  34. return 0;
  35. }

抄书copy了一下