You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UDP套接字编程中客户端无法接收服务器消息的问题排查

C语言多服务器-客户端架构:HELLO消息无法接收问题

问题描述

我用C语言实现了一个包含3台服务器和1个客户端的程序,逻辑是:客户端启动后持续监听端口,接收服务器发送的HELLO消息,将新上线的服务器加入已知列表。但目前客户端完全无法接收到服务器发送的HELLO消息。

客户端代码

int bytes_received = recvfrom(client_socket, buffer, MAX_BUFFER_SIZE, 0, NULL, NULL);

if (bytes_received == -1) {
    printf("ERROR: %s (%s:%d)\n", strerror(errno), __FILE__, __LINE__);
    exit(-1);
}

buffer[bytes_received] = '\0';

if (strncmp(buffer, "HELLO: ", 7) == 0) {
    
    char *content = buffer + 7;  
    printf("Received HELLO message from server: %s\n", content);
    printf("Received HELLO message from (%s:%d): %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer + 1);
    if (num_known_servers < MAX_SERVERS) {
        struct Server new_server;
        memcpy(&new_server.addr, (struct sockaddr_in *)(&client_addr), sizeof(struct sockaddr_in));
        new_server.last_message_time = time(NULL);
        known_servers[num_known_servers++] = new_server;
        char log_message[MAX_BUFFER_SIZE];
        snprintf(log_message, MAX_BUFFER_SIZE, "New server discovered at %s:%d", inet_ntoa(new_server.addr.sin_addr), ntohs(new_server.addr.sin_port));
        logMessage(log_message);
    }
} else {
    continue;
} 

服务器代码

char server_message[] = "HELLO: Hello from server";
            
if (sendto(server_socket, server_message, strlen(server_message), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)) == -1) {
    printf("ERROR: %s (%s:%d)\n", strerror(errno), __FILE__, __LINE__);
    exit(-1);
}        

核心排查方向

  • 地址端口有效性:确认服务器端的client_addr是否正确配置了客户端的IP和监听端口,避免消息发送到错误地址。
  • 套接字类型匹配:客户端和服务器必须统一使用UDP套接字(创建时指定SOCK_DGRAM),recvfrom/sendto是UDP专属接口。
  • 客户端绑定要求:客户端必须提前绑定固定端口,否则服务器无法定位客户端的接收端口;若未绑定,recvfrom需传入非NULL的地址参数获取发送方信息,但服务器仍需知道客户端端口才能主动发送。
  • 网络与防火墙限制:检查本地防火墙是否拦截UDP数据包,确保服务器与客户端在同一网络(跨网络需配置端口映射)。
  • 代码语法修复:客户端代码中原else if { continue; }存在语法错误,已修正为else { continue; },否则编译失败。
  • 字节序正确性:服务器设置client_addr的端口时需用htons()转换为网络字节序,IP地址需用inet_addr()或inet_pton()转换。
  • 缓冲区与字符串处理:确保MAX_BUFFER_SIZE足够容纳HELLO消息,避免截断导致匹配失败。

内容的提问来源于stack exchange,提问作者XXXCprt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 17:17:32