time.cpp
资源名称:1731.rar [点击查看]
上传用户:swkcbjrc
上传日期:2016-04-02
资源大小:45277k
文件大小:2k
源码类别:
游戏
开发平台:
Visual C++
- #include "stdafx.h"
- #include "winsock.h"
- #include "stdlib.h"
- void usage(char *name)
- {
- fprintf(stderr, "usage: %s [ip [port]]n", name);
- }
- int main(int argc,char *argv[])
- {
- SOCKET sock;
- struct sockaddr_in sa;
- int err;
- int servport = 5555; /* 默认去连接的端口 */
- char buff[256]; /*存放服务器端返回的信息 */
- WSADATA wsd;
- unsigned long uladdr; /* 转换后的服务器地址 */
- if (argc > 3 || argc < 2)
- {
- usage(argv[0]);
- return -1;
- }
- if (argc > 1)
- {
- uladdr = inet_addr(argv[1]);
- if (uladdr == INADDR_NONE)
- {
- usage(argv[0]);
- return -1;
- }
- }
- if (argc == 3)
- {
- servport = atoi(argv[2]);
- if (servport > 65535 || servport < 1)
- {
- /* 如不是合法端口,则退出*/
- usage(argv[0]);
- return -2;
- }
- }
- /* 初始化WinSock1.1 */
- if (WSAStartup(MAKEWORD(1,1), &wsd) != 0)
- {
- printf("WSAStartup( ) failed !n");
- return -3;
- }
- /* 创建连接套接字 */
- printf("create Socket ...n");
- sock = socket(AF_INET, SOCK_STREAM, 0);
- if (sock == INVALID_SOCKET)
- {
- fprintf(stderr, "Socket( ) failed: %dn", WSAGetLastError( ));
- return -4;
- }
- printf("[OK]n");
- /* 填充要连接的服务器地址结构 */
- memset(&sa, 0, sizeof(sa));
- sa.sin_family = AF_INET;
- sa.sin_port = htons(servport);
- sa.sin_addr.S_un.S_addr = uladdr;
- /* 连接服务器 */
- printf("connect ...n");
- err = connect(sock, (const sockaddr *)&sa,sizeof(sa));
- if (err != 0) {
- fprintf(stderr, "connect( ) failed: %dn", WSAGetLastError( ));
- return -5;
- }
- printf("[OK]n");
- /* 接收返回的时间/日期信息 */
- printf("recv data ...n");
- memset(buff, 0, sizeof(buff));
- if (recv(sock, buff, sizeof(buff), 0) == SOCKET_ERROR) {
- fprintf(stderr, " recv error !n");
- return -1;
- }
- printf("[OK]n");
- /* 输出返回的信息 */
- printf("Server Date/time : n%sn", buff);
- closesocket(sock); /* 关闭连接套接字 */
- WSACleanup( ); /* 释放资源 */
- return 0;
- }