accept()更改服务器套接字描述符

时间:2018-03-29 09:09:43

标签: c sockets

我正在实现一个简单的套接字。但是,服务器程序出现了分段错误问题,我发现在调用accept()函数后,服务器套接字描述符被更改为错误的值。我在下面附上了我的部分代码。我无法找到套接字描述符的值被accept()函数更改的原因。我的代码有什么问题?感谢。

while(1)
{
  readFdSet = allFdSet;

  // Call the select() function to check the change of input stream
  if(select(maxFd+1, &readFdSet, NULL, NULL, NULL) == -1)
  {
    printf("Fail to select the fd\n");
    exit(1);
  }

  // Check the connection request to serverSocket
  if(FD_ISSET(serverSocket, &readFdSet))
  {
    // Accept the connection request from the client
    clientAddrSize = sizeof(clientAddr);
    // It prints 'serverSocket: 3'
    printf("serverSocket: %d\n", serverSocket);
    clientSocket =  accept(serverSocket, (struct sockaddr *)&clientSocket, &clientAddrSize);
    // It prints 'serverSocket: 16777343'
    printf("serverSocket: %d\n", serverSocket);

    if(clientSocket == -1)
    {
      printf("Fail to accept a client\n");
      exit(1);
    }
    else
      printf("Accept a client, fd = %d\n", clientSocket);

    // Add the fd of clientSocket into allFdSet
    FD_SET(clientSocket, &allFdSet);

    if(clientSocket > maxFd)
    {
      maxFd = clientSocket;
    }
    continue;
  }

  for(int i=0; i<=maxFd; i++)
  {
    clientSocket = i;
    if(FD_ISSET(clientSocket, &readFdSet))
    {
      // Read the message from the client 
      memset(buff, 0, BUFF_SIZE);
      while(read(clientSocket, buff, BUFF_SIZE)>0)
      {
        printf("%s", buff);
        memset(buff, 0, BUFF_SIZE);
      }

      close(clientSocket);
      FD_CLR(clientSocket, &allFdSet);

      if(maxFd == clientSocket)
        maxFd--;

      printf("Close the connection\n");
    }
  }
}

1 个答案:

答案 0 :(得分:2)

clientSocket =  accept(serverSocket, (struct sockaddr *)&clientSocket, &clientAddrSize);

问题出在这里。 clientSocket是FD,而不是sockaddr,并且它的大小不是sizeof(clientAddr)。因此accept()会破坏clientSocket之前或之后的任何谎言,这可能是serverSocket或其他任何内容。

应该是:

clientSocket =  accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrSize);

正如@ChrisTurner首先暗示的那样。