Demonstrate Socket For Server Linux Unix C programming

cpp-program to demonstrate socket for server.
Important Function And keyword.
Initialize the socket
int sockfd=socket(AF_INET,SOCK_STREAM,0);
Get the Hostname
gethostname(hostname,48);
Assign the PortNumber
cout<<", port: "<<<"\n\n";
Source Code Programming For Server Socket 
#include<
sys/socket.h>
#include<arpa/inet.h>
#include<iostream.h>
#include<sys/types.h>
#include<string.h> i
nt makelistener() { int sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<0)
{
cerr<<"could not create socket\n";
return -1;
}
struct sockaddr_in s1;
bzero((char *) &s1,sizeof(s1));
s1.sin_family=AF_INET;
s1.sin_addr.s_addr=INADDR_ANY;
s1.sin_port=0;
if(bind(sockfd,(sockaddr *) &s1,sizeof(s1))<0)
{
cerr<<"could n't bind address to socket\n";
return -1;
}
char hostname[48];
gethostname(hostname,48);
size_t length;
length=sizeof(s1);
getsockname(sockfd,(sockaddr *) &s1,&length);
cout<<"\nlistening on host: "<<hostname;
cout<<", port: "<<ntohs(s1.sin_port)<<"\n\n";
if(listen(sockfd,1)<0)
{
PAGE NO.
54
54
SWARNA BHARATHI COLLEGE OF ENGINEERING MCA III SEM
cerr<<"couldn't listen().\n";
return -1;
}
cout<<"ready for incoming connections\n";
return sockfd;
}
int main()
{
int sockfd=makelistener();
if(sockfd<0)
return -1;
for( ; ;)
{
cout<<"server waiting for connections\n";
struct sockaddr_in s2;
size_t length=sizeof(s2);
int conn=accept(sockfd,(sockaddr *) &s2,&length);
cout<<"server accepted connection\t: "<<conn<<"\n";
char data[128];
char message1[128];
int ack1;
int msglen=read(conn,data,128);
cout<<"server got "<<msglen<<" byte message: "<<data<<"\n";
write(conn,&msglen,sizeof(msglen));
cout<<"enter message for client\n";
cin.getline(message1,128);
write(conn,message1,strlen(message1));
read(conn,&ack1,sizeof(ack1));
cout<<"the client got "<<ack1<<" bytes\n";
close(conn);
return 0;
}
return demonstrate socket for server

Related post