windows date time server:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
using namespace std;
#pragma comment(lib,"Ws2_32.lib")
#define IP_ADDRESS "210.47.24.11"
#define PORT 13
int main()
{
WSADATA Ws;
SOCKET ServerSocket, CientSocket;
struct sockaddr_in LocalAddr, ClientAddr;
int Ret = 0;
int AddrLen = 0;
HANDLE hThread = NULL;
//Init Windows Socket
if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
{
cout<<"Init Windows Socket Failed::"<<GetLastError()<<endl;
return -1;
}
//Create Socket
ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( ServerSocket == INVALID_SOCKET )
{
cout<<"Create Socket Failed::"<<GetLastError()<<endl;
return -1;
}
LocalAddr.sin_family = AF_INET;
LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
LocalAddr.sin_port = htons(PORT);
memset(LocalAddr.sin_zero, 0x00, 8);
//Bind Socket
Ret = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(LocalAddr));
if ( Ret != 0 )
{
cout<<"Bind Socket Failed::"<<GetLastError()<<endl;
return -1;
}
Ret = listen(ServerSocket, PORT);
if ( Ret != 0 )
{
cout<<"listen Socket Failed::"<<GetLastError()<<endl;
return -1;
}
cout<<"server startup"<<endl;
AddrLen = sizeof(ClientAddr);
CientSocket = accept(ServerSocket, (struct sockaddr*)&ClientAddr, &AddrLen);
if ( CientSocket == INVALID_SOCKET )
{
cout<<"Accept Failed::"<<GetLastError()<<endl;
}
cout<<"client connect::"<<inet_ntoa(ClientAddr.sin_addr)<<":"<<ClientAddr.sin_port<<endl;
stringstream ss;
string str;
SYSTEMTIME systime;
GetLocalTime(&systime);
ss<<systime.wYear<<"-"<<systime.wMonth<<"-"<<systime.wDay<<" "<<systime.wHour<<":"<<systime.wMinute<<":"<<systime.wSecond;
str=ss.str();
// cout<<str<<endl;
const char *buf = str.c_str();
// cout<<systime.wYear<<"-"<<systime.wMonth<<"-"<<systime.wDay<<" "<<systime.wHour<<":"<<systime.wMinute<<":"<<systime.wSecond<<endl;
send(CientSocket,buf,strlen(buf)+1,0);
closesocket(ServerSocket);
closesocket(CientSocket);
WSACleanup();
system("pause");
return 1;
}
linux get date tiime client:
#include<netinet/in.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<stdarg.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/un.h>
#define MAXLINE 4096
int main(int argc, char **argv)
{
int sockfd,n;
char recvline[MAXLINE+1];
struct sockaddr_in servaddr;
if(argc!=2)
printf("usage:a.out<IPaddress");
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("socket error");
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",argv[1]);
if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
printf("fconnect error");
while((n=read(sockfd,recvline,MAXLINE))>0)
{
recvline[n]=0;
if(fputs(recvline,stdout)==EOF)
printf("fputs error");
printf("\n");
}
if(n<0) printf("read error");
exit(0);
}