i wrote a TCP server in C language. Code is as follows
Code:
using namespace std;
#include<arpa/inet.h>
#include<stdlib.h>
#include<fstream>
#include<iostream>
main()
{
int sockfd;
struct sockaddr_in cli_addr,server_addr;
char buffer[100];
ofstream myfile;
socklen_t clilen;
if( (sockfd = socket(PF_INET,SOCK_STREAM,0)) < 0 )
{
cout<<"server - unable to open the socket."<<endl;
exit(1);
}
server_addr.sin_family = PF_INET;
server_addr.sin_addr.s_addr = inet_addr("172.16.16.33");
server_addr.sin_port = htons(2009);
if( bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr)) < 0 )
{
cout<<"Server - unable to bind the local address";
exit(1);
}
listen(sockfd,1);
while(1)
{
clilen = sizeof(cli_addr);
bzero(buffer,100);
if(accept(sockfd, (struct sockaddr*)&cli_addr, &clilen) < 0)
{
cout<<"Server - unable to accept the connection from client.";
exit(1);
}
if(recv(sockfd,buffer,100,0)<0)
{
cout<<"Server - unable to read the data from the socket.";
exit(1);
}
myfile.open("data_file",ios::app);
if(!myfile.is_open())
{
cout<<"Server - Unable to open file to write alert"<<endl;
exit(1);
}
myfile<<buffer;
myfile.close();
}
close(sockfd);
}
I tried the recv / read function for reading the data from the socket.
But it is not able to read the data from the socket. Always it is returning -1 and exit function is executing. I tried even as root user. Still same problem. Don't know where is the bug.
Client program is working correctly. it returning the correct number of bytes when I use write/send function.
can any one please help me sorting out this issue.
thanks.