gpt4 book ai didi

recv() 函数上的 C 段错误 11

转载 作者:行者123 更新时间:2023-11-30 19:44:46 27 4
gpt4 key购买 nike

我对 C 套接字有疑问。我在 recv(int socket, void *buffer, size_t length, int flags); 函数上出现 Segmentation failure: 11 。我在连接功能中打印了服务器IP。这应该意味着该套接字已正确初始化。

使用函数recv的函数:

int receive_packet(SOCKET *socket, char *packet)
{
int bytes;
char data_buffer [2000] = {0};

bytes = recv(*socket, data_buffer, sizeof(data_buffer), 0);

if (bytes == 0)
{
return 0;
}

else if (bytes == SOCKET_ERROR)
{
printf("Error: failed to receive packet\n");

return SOCKET_ERROR;
}

else
{
memset (packet, 0, bytes);

strcpy (packet, data_buffer);

return bytes;
}
}

主函数在哪里调用函数recv:

int main(int argc, char *argv[])
{
SOCKET command_socket;
int port;
char *host;
char *username;
char *password;
char *packet = NULL;

host = argv[1];
port = atoi(argv[2]);
username = argv[3];
password = argv[4];

printf("BEFORE: %d\n", command_socket);

command_socket = connect_to_server(host, port);

printf("AFTER: %d\n", command_socket);

receive_packet(&command_socket, packet);

printf("Packet: %s\n", packet);

return 0;
}

输出:

BEFORE: 0
Connected successfully.
AFTER: 3
Segmentation fault: 11

有什么想法吗?!

附注我的基于 UNIX 的操作系统是 OS X。

最佳答案

根据我的理解,SOCKET应该是int类型来表示文件描述符。并且您必须将 NULL 传递给 receive_packet,当取消引用该指针时,您会遇到段故障,这是我能想到为什么您在 recv 中遇到段故障的唯一原因。

关于recv() 函数上的 C 段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27382022/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com