I am trying socket programming and with the server code:
while(1) {
sin_size = sizeof (their_addr);
new_fd = accept(sockfd,(struct sockaddr *)&their_addr, &sin_size);
if(new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr*)&their_addr),s,sizeof(s));
cout<<"got connection from" << s << endl;
if((pid = fork()) == 0){//child
close(sockfd);
if(send(new_fd,"hello world!",12,0) == -1) {
perror("send");
close(new_fd);
exit(0);
}
char buf[50];
int numbytes;
if((numbytes = recv(new_fd,&buf,50,0)) == -1) {
perror("receive");
close(new_fd);
exit(0);
}
buf[numbytes] = '\0';
cout<<"numbytes" << numbytes <<endl;
cout<<"server received " << buf <<endl;
}
close(new_fd);
}
this code gives me a bad file descriptor, however when i comment the close(sockfd), the code runs fine. Since I am forking to a new child process and closing the listening port , why am I getting a bad file descriptor? Is there something I am missing here.