linux套接字接受总是失败

时间:2016-03-03 14:42:50

标签: linux sockets tcp server client

我有一个相对简单的服务器,应该打开服务器套接字并接受一个客户端套接字连接。

if(!(STARTUP))
{
// CAN Socket öffnen
can_soc = initialize_CAN();

// TCP Socket öffnen
tcp_soc = initialize_TCP(strtol(argv[1],NULL,10));

STARTUP = 1;
}


// Jede empfangene CAN Botschaft auf TCP umleiten
while(!(EXIT_FLAG))
{

if(!(CLIENT_CONNECTED)) // Wenn keiner verbunden ist, wird gelistened
{
    // LISTEN //
        listen(tcp_soc,2);

    std::cout << "Waiting for incoming TCP connection...\n";

    c = sizeof(struct sockaddr_in);

    tcp_client_soc = accept(tcp_soc, (struct sockaddr *)&client, (socklen_t*)&c);

    if(tcp_client_soc < 0)
    {
    std::cout << "ERROR: accept failed\n";
    EXIT_FLAG = 1;
    return 0;
    }
    else
    {
    std::cout << "Connection from " << inet_ntoa(client.sin_addr) << " accepted!\n";
    // --> NEUER CLIENT AKZEPTIERT //
    CLIENT_CONNECTED = 1;
    }
}
else            // ansonsten: CAN auf TCP leiten
{
    std::cout << "nop" << std::endl;
}

}

现在的问题是,程序始终终止于“错误:接受失败”,这意味着接受总是在没有建立连接的情况下传递-1(未设置O_NONBLOCK)。

int initialize_TCP(int pPort)
{
    int tcp_soc;

    std::cout << "Creating TCP socket and binding to PORT: " << pPort << "... ";

    tcp_soc = socket(AF_INET, SOCK_STREAM, 0);

    if(tcp_soc == -1)
    {
        std::cout << "ERROR: Could not create socket!\n";

    EXIT_FLAG = 1;
    }


    server.sin_addr.s_addr = INADDR_ANY;    //do not specify IP (got a server here)
    server.sin_family = AF_INET;
    server.sin_port = htons(pPort);

    // BIND //

    if(bind(tcp_soc,(struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cout << "Binding failed! Restarting network service ...\n";

        system("/etc/init.d/networking restart");   //Restarted Network Servcie wenn Binding nicht geht

        std::cout << "Binding again... ";
        bind(tcp_soc,(struct sockaddr *)&server, sizeof(server));
        std::cout << "OK\n";
    }


    std::cout << "OK\n";
}

问题出在哪里?也许每次都有未知的连接?还是语法问题?

1 个答案:

答案 0 :(得分:0)

发现问题,套接字不存在,因此ERRNO提供了代码88。 这是因为没有正确返回套接字描述符。