《UNIX网络编程》时间获取客户端/服务器程序,WIN/MAC下运行
// client#include <winsock2.h>
#include <stdio.h>
int main()
{
WSAData wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
int sockfd, n;
char recvline[1024];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
struct hostent *host_entry = gethostbyname("localhost");
servaddr.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;
int c = connect(sockfd, (sockaddr*)&servaddr, sizeof(servaddr));
while ((n = recv(sockfd, recvline, 1024, 0)) > 0)
{
recvline[n] = 0;
fputs(recvline, stdout);
}
getchar();
return 0;
}
// server
#include <winsock2.h>
#include <stdio.h>
#include <time.h>
int main()
{
WSAData wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[1024];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
servaddr.sin_addr.s_addr = INADDR_ANY;
bind(listenfd, (sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 5);
for (;;)
{
connfd = accept(listenfd, 0, 0);
ticks = time(NULL);
sprintf(buff, "%.24s\r\n", ctime(&ticks));
send(connfd, buff, strlen(buff), 0);
}
getchar();
return 0;
}
// MAC client
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int sockfd, n;
char recvline[1024];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7650);
struct hostent *host_entry = gethostbyname("localhost");
servaddr.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;
int c = connect(sockfd, (sockaddr*)&servaddr, sizeof(servaddr));
while ((n = recv(sockfd, recvline, 1024, 0)) > 0)
{
recvline[n] = 0;
fputs(recvline, stdout);
}
getchar();
return 0;
}
// MAC server
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[])
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[1024];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(7650);
servaddr.sin_addr.s_addr = INADDR_ANY;
bind(listenfd, (sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 5);
for (;;)
{
connfd = accept(listenfd, 0, 0);
ticks = time(NULL);
sprintf(buff, "%.24s\r\n", ctime(&ticks));
send(connfd, buff, strlen(buff), 0);
}
getchar();
return 0;
}
[此贴子已经被作者于2015-12-18 11:39编辑过]