【问题标题】:Linux Socket Programming : listen() call showing unexpected behaviourLinux Socket 编程:listen() 调用显示意外行为
【发布时间】:2016-06-09 11:50:14
【问题描述】:

我正在为服务器编写一个简单的套接字程序,但在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;
}

我没有听到“正在听...”。

【问题讨论】:

    标签: linux sockets network-programming


    【解决方案1】:

    这是由于缓冲了 sdtout 数据。做fflush(stdout),给出了正确的打印。并且该进程现在被阻止在预期位置accept()

    【讨论】:

      猜你喜欢
      • 2017-12-17
      • 2015-04-09
      • 2021-07-30
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多