cpp-program To Demonstrate Socket For Client.

C Program To Demonstrate Socket  For Client. Her I mention the Important Function to perform the socket.
cin.getline(server_host,80);
struct hostent *hostptr=gethostbyname(server_host);
bcopy(hostptr->h_addr, (char *) &dest.sin_addr, hostptr->h_length);#include<iostream.h>
Source Coding For socket Client
#include<sys/types.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int serverconnect()
{
char server_host[80];
u_short server_port;
cout<<"enter the hostname the server is running on\n";
cin.getline(server_host,80);
cout<<"enter the port number the server is listening on\n";
cin>>server_port;
cin.ignore(1,'\n');
int sock;
sock=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in dest;
bzero((char *) &dest,sizeof(dest));
struct hostent *hostptr=gethostbyname(server_host);
if(NULL==hostptr)
{
cerr<<"error looking up host "<<server_host<<"\n";
return -1;
}
dest.sin_family=AF_INET;
bcopy(hostptr->h_addr, (char *) &dest.sin_addr, hostptr->h_length);
dest.sin_port=htons(server_port);
cout<<"trying to connect\n";
if(connect(sock, (sockaddr *) &dest, sizeof(dest)))
{
PAGE NO.
56
56
SWARNA BHARATHI COLLEGE OF ENGINEERING MCA III SEM
cout<<"couldn't connect\n";
return -1;
}
cout<<"connection established\n";
return sock;
}
int main()
{
int conn=serverconnect();
if(conn<0)
return -1;
char data[128];
char message[128];
int ack;
cout<<"enter message for server: \n";
cin.getline(message,128);
write(conn,message,strlen(message));
read(conn,&ack,sizeof(ack));
cout<<"the server got "<<ack<<" bytes\n";
int msglen=read(conn,data,128);
cout<<"client got "<<msglen<<" bytes message: "<<data<<" \n ";
write(conn,&msglen,sizeof(msglen));
close(conn);
return 0;
}
demonstrate socket for client.

Post a Comment

0 Comments