Linux套接字编程:listen()调用显示意外行为

时间:2016-06-09 11:50:14

标签: linux sockets network-programming

我正在为服务器编写一个简单的套接字程序,我在listen()调用中挂起了一个挂起。令人惊讶的是,这段代码挂起了:

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

怎么可能这样?这是我的完整代码供参考:

#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;
}

我没有得到“倾听......”。

1 个答案:

答案 0 :(得分:3)

这是由于缓存了sdtout数据。做fflush(stdout),给出了正确的印刷品。此过程现已在预期位置accept()被阻止。