Linux 套接字程序只是冻结而没有错误

Linux socket program just freezes without error

本文关键字:有错误 冻结 套接字 程序 Linux      更新时间:2023-10-16

我最近使用Windows进行套接字编程,但我的作业要求学生使用Linux Socket header(sys/socket.h(而不是Windows。所以我从零开始,但程序冻结,即使它是一个非常简单的程序,它什么都不做,只在建立连接时打印一条消息。

服务器.cpp

#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
#define BACKLOG 10
int main(void){
    int sockfd, new_fd;
    struct sockaddr_in my_addr;
    struct sockaddr_in their_addr;
    socklen_t sin_size;
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){
        perror("Socket creation failed");
        exit(1);
    }
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(PORT);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr))==-1){
        perror("Socket binding failed");
        exit(1);
    }
    if(listen(sockfd, BACKLOG) == -1){
        perror("Socket listening failed");
        exit(1);
    }
    sin_size = (socklen_t)sizeof(struct sockaddr_in);
    while(true){
        printf("Loop Test"); // This is not displayed at all
        if((new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size))==-1){
            perror("Connetion accepting failed");
            exit(1);
        }
        printf("Server got connection from %sn", inet_ntoa(their_addr.sin_addr));
    }
    return 0;
}

客户端.cpp

#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
int main(void){
    int sockfd;
    struct sockaddr_in their_addr;
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
        perror("Socket generating failed");
        exit(1);
    }
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(PORT);
    their_addr.sin_addr.s_addr = INADDR_LOOPBACK;
    if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) == -1){
        perror("Connection failed");
        exit(1);
    }
    printf("Loop test"); // This is not displayed no matter if server is on or not
    return 0;
}

正如我在代码中提到的,它只是停止,并且不显示错误和 printf(用于调试(。为什么会这样?(我正在使用 Ubuntu(

您的程序有两个问题。第一个相对较小,就是你不要用"n"结束你的printf语句。因此,输出是缓冲的,您不会立即看到它。

但是,如果您没有一个简单但烦人的错误,那么仅此将不可见(尽管它确实使调试变得更加困难,因为您不确定发生了什么( - 您无法使用 htonl 将INADDR_LOOPBACK转换为大端序。具有讽刺意味的是,你这样做是为了INADDR_ANY(虽然好的风格并没有做任何真正的事情,因为 0 总是 0(,但不要在真正重要的地方这样做。