0% found this document useful (0 votes)
36 views

Iterative Server

This document contains code for a server program and client program that communicate over a socket. The server program prints the client's IP address and port number, gets the current time, and sends the time to the client. The client program connects to the server and receives the time sent by the server.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Iterative Server

This document contains code for a server program and client program that communicate over a socket. The server program prints the client's IP address and port number, gets the current time, and sends the time to the client. The client program connects to the server and receives the time sent by the server.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/* SERVER PROGRAM THAT PRINTS CLIENTS IP ADDRESS AND PORT NUMBER AND SENDS TIME AND DAY TO THE

CLIENT */ #include #include "unp.h" <time.h>

main(int argc, char **argv) { int socklen_t struct sockaddr_in char time_t

listenfd, connfd; len; servaddr, cliaddr; buff[MAXLINE]; 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(4567); /* daytime server */ 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)); write(connfd, buff, strlen(buff)); close(connfd); } } /* Client Program */ #include<unp.h> #include<sys/types.h> #include<sys/socket.h> 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(4567); //port number if given as 13 it will not work so use 4567 or dynamic ports

if(inet_pton(AF_INET,argv[1],&(servaddr.sin_addr))<=0) printf("inet_pton error for %s\n",argv[1]); if(connect(sockfd,(struct sockaddr *) &servaddr,sizeof(servaddr))<0) printf("connect Error\n"); while((n=read(sockfd,recvline,MAXLINE))>0) { recvline[n]=0; if(fputs(recvline,stdout)==EOF) printf("fputs error\n"); } if(n<0) printf("read error\n"); exit(0); }

You might also like