我遇到了C套接字问题。我Segmentation fault: 11
函数recv(int socket, void *buffer, size_t length, int flags);
。我在连接功能中打印了服务器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
任何想法为什么?!
P.S。我的基于UNIX的操作系统是OS X.
答案 0 :(得分:0)
据我所知,SOCKET应该是int
类型来表示文件描述符。并且你必须向receive_packet
传递一个NULL,当解除引用该指针时,你得到了段falut,这是我能想到为什么你在recv中得到一个段falut的唯一原因。