Reputation: 9803
I am trying to get my feet wet with network programming. I have created a server, that accepts a connection from a web client.
At some point (I can not recall when) it broke, and for the life of me, I can not get it fixed.
Could someone at least provide me with some pointers? (No pun intended)
I have tried all there is, read the whole web, including the gnu c library documentation (I am on linux) but still no luck.
EDIT: Description of the problem: My client software manages to connect, however the server software doesn't report on that, and seems to get stuck at the accept() function.
My code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "lib/error.h"
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char *argv[])
{
int socketfd = 0, connfd = 0; // socket, and connection file descriptors
struct sockaddr_in serv_addr; // struct that will get filled with host info
struct sockaddr_in cli_addr; // struct that will get filled with peer info
int status; // Used for various status controling and error messaging throughout the program
char sendBuff[1025]; // buffer to allow for storage of items to be sent
socklen_t cli_size = sizeof(cli_addr);
time_t ticks;
socketfd = socket(AF_INET, SOCK_STREAM, 0); // Creating a socket
if (socketfd == -1) error("Failed to create socket.", 4);
memset(&serv_addr, '0', sizeof(serv_addr)); // zeroing out the location of serv_addr
memset(&cli_addr, '0', sizeof(cli_addr)); // zeroing out the location of serv_addr
memset(sendBuff, '0', sizeof(sendBuff)); // zeroing out the locaiton of sendBuff
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
status = bind(socketfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if (status == -1) error("Failed to bind socket.", 4);
listen(socketfd, 10);
while(1)
{
connfd = accept(socketfd, (struct sockaddr *) &cli_addr, (socklen_t *) &cli_size);
if (connfd == -1) error("Failed during accepting the peer connection at socket.", 3);
printf("Client connected: %d:%d", cli_addr.sin_addr.s_addr, cli_addr.sin_port);
close(connfd);
sleep(1);
}
return 0;
}
Upvotes: 0
Views: 4259
Reputation: 182724
As speculated in the comments, the problem is buffering. In a nutshell, the client connects, accept
returns a valid socket and printf
is called but the output simply doesn't get onto the screen.
As Roddy mentioned, adding a newline might fix it because on many implementations stdout
is line-buffered, i.e. when you write a newline it automatically flushes everything. However, that isn't required by the standard so the safest cleanest way to ensure the output does go to the device is fflush
.
As Chris Hayes mentioned, you probably want memset(&serv_addr, 0, sizeof serv_addr)
and you don't need the cast in (socklen_t *) &cli_size
.
Upvotes: 2