套接字程序在接受时退出

时间:2012-12-22 22:46:06

标签: c sockets

由于一些莫名其妙的原因,这个C ++程序在接受套接字时退出。接受套接字,这反映在客户端,但服务器会自动爆炸。

完整的代码如下:

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

#define BUF_SIZE 500
#define BACKLOG 50

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage %s port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in addr;
    struct sockaddr_storage theiraddr;
    socklen_t addrlen;
    char buf[BUF_SIZE];

    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    theiraddr.ss_family = AF_INET;

    int sockfd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0);

    if (sockfd == -1)
    {
        printf("Sock Error!\n");
        exit(EXIT_FAILURE);
    }

    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
    {
        printf("Bind Error!\n");
        exit(EXIT_FAILURE);
    }

    if (listen(sockfd, BACKLOG) == -1)
    {
        printf("Listen Error!\n");
        exit(EXIT_FAILURE);
    }

    addrlen = sizeof(theiraddr);
    int accepted;

    for ( int i = 0; ; i++ )
    {
        usleep(100000);

        errno = 0;
        printf("pre-accept\n");
        accepted = accept(sockfd, (struct sockaddr *)&theiraddr, &addrlen);
        printf("%i", accepted == -1); //this line does not get executed

        if(errno == EWOULDBLOCK)
        {
            printf("WOULDBLOCK %i\n", i);
            continue;
        }
        else if(accepted == -1)
        {
            printf("TERRIBLE TRAGEDY\n");
        }

        printf("Accepted.\n");

        char msg[] = "You have connected.";

        send(sockfd, msg, sizeof(msg), 0);

        close(accepted);

    }
    close(sockfd);
}

1 个答案:

答案 0 :(得分:2)

您没有看到错误消息,因为格式字符串末尾没有\nstdout是行缓冲的。在任何情况下都使用stderr进行错误输出。

你真正的错误似乎就是这个

send(sockfd, msg, sizeof(msg), 0);

我想你的意思是发送accepted accept提供给你的文件描述符进行通信。