Hey i was just writing a simple server i'm using accept() in a loop to emit constant greeting but i dont know why my code stucks at single send() i mean it asks for input only once --> it asks for input --> i give input--> it emits succsfully to port 3490 or whatever in my code ---> but it does not asks for another input even though my code is in a loop Help me there check out my code -->

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

# define BACKLOG 5

int main(int argc,char *argv[]){

    int status,socket_result,new_fd;
    struct addrinfo hints,*result;
    struct sockaddr_storage their_addr;
    socklen_t addr_size;

    memset(&hints,0,sizeof hints);

    hints.ai_family = AF_INET;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_socktype = SOCK_STREAM;

 status = getaddrinfo(NULL,"3490",&hints,&result);

socket_result = socket(result->ai_family,result->ai_socktype,result->ai_protocol);

if(socket_result == -1){
    printf("server might be alrey running");
    return 1;



char data[13];


addr_size = sizeof their_addr;

new_fd = accept(socket_result,(struct sockaddr *)&their_addr,&addr_size);
printf("enter input \n");
printf("about to send your input");
printf("input sent");}

return 0;

2 Years
Discussion Span
Last Post by L7Sqr

The next time you loop through you are calling listen and accept again. First, I would move the listen outside of the loop. Second, accept is a blocking call - that is, if no other connection attempts are made it will wait there indefinitely.

A general approach to this situation is to fork a child to handle the newly accepted socket or to use a thread instead of a new process.


Hey I got it about using fork() but in case of listen() n accept() im confused cause compiler cursor should move down after send() and should printf("input sent"); but it seems to be freezed at send() i mean send is not returning anything.


or can you please modify my code for fork part it would be great help thanks


I'm not sure what a compiler cursor is - I'm assuming it to be the prompt on your terminal?

Can you print the return value from your send call (it returns a value you should be reading). Instead of printf, however, use fprintf to stderr.

I suspect that you are running into a buffering issue that is complicating the problem for you. printf is a buffered output statement meaning that it isn't necessarily sent directly to the screen when it returns. To overcome this you can issue an fflush (stdout) after the printf or you can use fprintf (stderr, ...) instead.

Try replacing all your printf statements with fprintf (stderr, ...) and see if that changes things for you.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.