我正在尝试为我的程序编写一个TCP套接字接口(interface),并且出现了accept()错误(我认为)。为此,我创建了一些简化的测试代码。
首先,我做了一些设置

int server_socket = 0;
server_socket = socket(AF_INET, SOCK_STREAM, 0);

int accepted_connection = 0;

struct sockaddr_in server_address;
server_address.sin_port = htons(9001);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;

struct sockaddr_in client_address;
client_address.sin_port = 0;
client_address.sin_family = AF_INET;

char * server_socket_read_buffer[100] = {0};
int server_socket_read_length = 0;

所有非常简单的东西。只需分配一些变量即可。接下来我绑定(bind)并听
if (bind(server_socket,(struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
    perror("Bind() on server_socket has failed\n");
}

if (listen(server_socket, 10) < 0)
{
    perror("Listen() on server_socket has failed\n");
}

接下来是我认为我有问题的部分
printf("Attempting accept!\n");
if (accepted_connection = accept(server_socket, (struct sockaddr *)NULL, NULL) < 0)
{
    perror("Accept failed\n");
}
sleep(10);
if (server_socket_read_length = read(accepted_connection, &server_socket_read_buffer, server_socket_read_length) < 0)
{
    perror("Read failed\n");
}
printf("Read %d bytes from socket\n", server_socket_read_length);
for (int i = 0; i<server_socket_read_length;i++)
{
    printf("%x\n",server_socket_read_buffer[i]);
}

编译并运行。当我在命令“nc 127.0.0.1 9001”中使用nc时,我获得了连接,但未读取任何数据。特别是我得到0字节的数据。我认为这可能是由于accept行中的NULL所致,但是将其更改为适当的结构和长度会阻止我的代码编译。

如果有人能告诉我我在做什么错,我将不胜感激。

最佳答案

有几个错误:

  • INADDR_ANY是主机字节顺序的,需要像htonl(INADDR_ANY)一样转换为网络之一。但这并不重要,因为常量INADDR_ANY被定义为0

  • char * server_socket_read_buffer[100]
    

    应该
    char server_socket_read_buffer[100]
    

  • read(accepted_connection, &server_socket_read_buffer, server_socket_read_length)
    

    应该
    read(accepted_connection, server_socket_read_buffer, sizeof server_socket_read_buffer)
    
  • 关于c - c中的TCP套接字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31253443/

    10-13 03:01