/*CLIENT PROGRAM OF ECHO SERVER CLIENT*/
/*save this code
as file name:echo_client.c
COMPILE:-
cc echo_client.c -o echo_client.out
RUN:-
./echo_client.out
OR RUN BY PROVIDING SERVER ADDRESS AND PORT NUMBER
./echo_client.out <server_address> <portnumber>
example:-
./echo_client.out 192.168.0.1 1024
NOTE:
SERVER PROGRAM MUST RUN BEFORE CLIENT PROGRAM
*/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<sys/socket.h>
#define SERV_ADDR "127.0.0.1"
#define PORT_NO 2048
int main(int argc,char *argv[])
{
int ser_sd;
int buf_len;
char buffer[256]={0};
int port;
struct sockaddr_in server_info;
/* CREATION OF A SOCKET FOR CONNECTION TO SERVER*/
ser_sd=socket(PF_INET,SOCK_STREAM,0);
if(ser_sd==-1)
{
perror("socket():");
exit(EXIT_FAILURE);
}
/*PREPARE SERVER INFORMATION TO sockaddr_in STRUCTURE*/
/////////////as garbage can make problems//////////
bzero(&server_info,sizeof(struct sockaddr_in));
server_info.sin_family=PF_INET;
printf("argc=%d\n",argc);
if(argc==3)
{
port=atoi(argv[2]);
server_info.sin_port=htons(port);
server_info.sin_addr.s_addr=inet_addr(argv[1]);
}
else
{
server_info.sin_port=htons(PORT_NO);
server_info.sin_addr.s_addr=inet_addr(SERV_ADDR);
}
/*NOW SERVER STRUCTURE READY FOR USE TO CONNECT SERVER*/
/*CONNECT FUNCTION FOR CONNECT TO SERVER USING SERVER INFO
PRESENT IN THE server_info STRUCTURE*/
if(connect(ser_sd,(struct sockaddr *)&server_info,sizeof(server_info)))
{
perror("connect: ");
exit(EXIT_FAILURE);
}
printf("conection sucess\n");
/*CONNECTION TO SERVER SUCESS NOW WE ARE READY TO PASS MESSAGE*/
/*IT IS VERY SIMPLE YOU CAN USE SIMPLE READ WRITE FUNCTION
AS IT IS A REGULAR FILE DESCRIPTOR*/
while(1)
{
bzero(buffer,sizeof(buffer));/*FOR CLEARING THE PREVIOUS CONTENT*/
scanf(" %[^\n]s",buffer); /*ACCEPTING A MESSAGE FROM KEY BOARD FOR
SEND*/
write(ser_sd,buffer,255); /*use for writing to server*/
if(!(strcmp(buffer,"EXIT")))
{break;
}
buf_len=read(ser_sd,buffer,255); /*reading echo message from server*/
buffer[buf_len]='\0';
printf("%s\n",buffer);
}
/*CLOSING OF SERVER SOCKET DESCRIPTOR*/
if(shutdown(ser_sd,SHUT_RDWR))
{
perror("shutdown:");
exit(EXIT_FAILURE);
}
printf("socket is properly closed\n");
}
Thursday, 26 July 2012
SIMPLE TCP ECHO CLIENT PROGRAM USING LINUX SOCKET
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment