In the following program, we will demonstrate, how a connection can be established between client and server using Transport Layer Protocol - TCP. This code is self-explanatory. Hence, first, you will learn to develop server-side applications. Then, you will learn to develop client-side applications.
First, define a header file "unp.h" as follow. We will use this header file in other programs.
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/un.h>
#define MAXLINE 4096
#define LISTENQ 2
Source Code of the echo server
#include <stdio.h>
#include <time.h>
#include "unp.h"
int main(int argc, char *argv[])
{
pid_t p, q;
int listen_file_descriptor, connfd;
struct sockaddr_in server_address;
char buffer[MAXLINE];
time_t clock_tick;
listen_file_descriptor = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(8000);
bind(listen_file_descriptor, (struct sockaddr *)&server_address, sizeof(server_address));
listen(listen_file_descriptor, LISTENQ);
while(1)
{
connfd = accept(listen_file_descriptor, (struct sockaddr *)NULL, NULL);
p = fork();
if(p == 0)
{
q = getpid();
printf("%d", &q);
close(listen_file_descriptor);
clock_tick = time(NULL);
snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&clock_tick));
write(connfd, buffer, strlen(buffer));
close(connfd);
exit(0);
}
close(connfd);
}
}
Source Code of the echo Client
#include <stdio.h> #include "unp.h" int main(int argc,char *argv[]) { int socket_file_descriptor, n; char recvline[MAXLINE+1]; struct sockaddr_in server_address; if(argc!=2) { printf("usage:client <IPaddress>"); exit(0); } if ((socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0)) < 0) printf("socket error"); bzero(&server_address, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(8000); if((server_address.sin_addr.s_addr = inet_addr(argv[1])) <= 0) { printf("inet_pton error for %s", argv[1]); exit(0); } if(connect(socket_file_descriptor,(struct sockaddr *) &server_address, sizeof(server_address)) < 0) printf("connect error"); while((n = read(socket_file_descriptor,recvline,MAXLINE)) > 0) { recvline[n] = 0; if(fputs(recvline, stdout) == EOF) printf("fputs error"); } if(n < 0) printf("read error"); exit(0); }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.