客户端程序:
通过服务器返回当前的时间和日期。
#include "unp.h"
#include "my_err.h"
int main(int argc, char** argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if (argc != 2)
err_quit("usage:a.out<IPaddress>");
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_sys("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)
err_quit("inet_pton error for %s", argv[1]);
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) < 0)
err_sys("connect error");
while ((n = read(sockfd, recvline, MAXLINE)) > 0)
{
recvline[n] = 0;
if (fputs(recvline, stdout) == EOF)
err_sys("fputs error");
服务器端程序:
获得客户端端的IP和端口号。inet_ntop将套接字地址结构中的32位IP地址转换为一个点分十进制ASCII字符串,调用nthos将16位的端口号从网络字节序转换为主机字节序。
int main(int argc, char** argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
teme_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(13);
bind(listenfd, (SA*)&servaddr, sizeof(servaddr));
listen(listenfd, LISTENQ);
for (;;)
{
len = sizeof(cliaddr);
connfd = accept(listenfd, (SA*)&cliaddr, &len);
printf("connection from %s,port %d \n", inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),ntohs(cliaddr.sin_port));
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
crite(connfd, buff, strlen(buff));
close(connfd);
}
}