InsaneCoder
InsaneCoder

Reputation: 8268

Linux Socket Programming : listen() call showing unexpected behaviour

I was writing a simple socket program for a server, where I got a hang in listen() call. Surprisingly, this piece of code hangs :

if((res = listen(sockfd, 5)) == -1)
    {
        perror("Error in listening over socket");
        exit(1);
    }

How come this is possible? Here's my full code for reference :

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define MYPORT 7891

int main()
{
    int sockfd, newfd, res;
    struct sockaddr_in my_addr, their_addr;
    socklen_t their_addr_size;
    char msg[100] = {'\0'};

    /* open a socket for the server */
    if((sockfd = socket(AF_INET, SOCK_STREAM,0)) == -1)
    {
        perror("Error opening socket");
        exit(1);
    }

    printf("Socket opened successfully\n");

    /* specify the interface details, where the server should listen for incoming messages. It is set by bind */
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    my_addr.sin_addr.s_addr = INADDR_ANY; /* listen on every interface, eth0, wlan, whatever f**kin place */
    memset(&(my_addr.sin_zero),0,8);
    if((res = bind(sockfd, (struct sockaddr *)&(my_addr), sizeof(struct sockaddr_in))) == -1)
    {
        perror("Error while bind()");
        exit(1);
    }

    printf("Bind() is successfull\n");

    /* listen on the socket, setting the waiting queue size to max 5 connections. Other connections will get ECONNREFUSED error */
    if((res = listen(sockfd, 5)) == -1)
    {
        perror("Error in listening over socket");
        exit(1);
    }
    // if(listen(sockfd,5)==0)
    //   printf("Listening\n");
    // else
    //   printf("Error\n");


    printf("Listening....");

    /* accept incoming request */
    their_addr_size = sizeof(struct sockaddr_in);
    if((newfd = accept(sockfd, (struct sockaddr *)&their_addr, &their_addr_size)) == -1)
    {
        perror("Error accepting connection");
        exit(1);
    }

    /* write data */
    printf("Enter the data to be sent\n");
    while(1)
    {
        scanf("%s",msg);
        write(newfd, msg, strlen(msg));
    }

    /* though it never comes here due to infinite while loop */
    close(newfd);
    close(sockfd);
    return 0;
}

I am not getting "Listening...".

Upvotes: 1

Views: 103

Answers (1)

InsaneCoder
InsaneCoder

Reputation: 8268

It was due to the sdtout data buffered. Doing fflush(stdout), gave the proper print. And the process is now blocked at expected position accept().

Upvotes: 3

Related Questions