bind()失败,Windows套接字错误10038

时间:2010-05-23 13:23:20

标签: c++ windows sockets bind

我正在尝试编写一个简单的程序,它将接收最多20个字符的字符串并将该字符串打印到屏幕上。

代码编译,但我得到一个bind()失败:10038。在查找msdn上的错误号(在nonsocket上的套接字操作)后,我改变了一些代码

int sock;

SOCKET sock

哪个不应该有所作为,但一个人永远不会知道。

以下是代码:

#include <iostream>
#include <winsock2.h>
#include <cstdlib>
using namespace std;

const int MAXPENDING = 5;
const int MAX_LENGTH = 20;

void DieWithError(char *errorMessage);

int main(int argc, char **argv)
{
  if(argc!=2){
    cerr << "Usage: " << argv[0] << " <Port>" << endl;
    exit(1);
  }

  // start winsock2 library
  WSAData wsaData;
  if(WSAStartup(MAKEWORD(2,0), &wsaData)!=0){
    cerr << "WSAStartup() failed" << endl;
    exit(1);
  }

  // create socket for incoming connections
  SOCKET servSock;
  if(servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET)
    DieWithError("socket() failed");

  // construct local address structure
  struct sockaddr_in servAddr;
  memset(&servAddr, 0, sizeof(servAddr));
  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = INADDR_ANY;
  servAddr.sin_port = htons(atoi(argv[1]));

  // bind to the local address
  int servAddrLen = sizeof(servAddr);
  if(bind(servSock, (SOCKADDR*)&servAddr, servAddrLen)==SOCKET_ERROR)
    DieWithError("bind() failed");

  // mark the socket to listen for incoming connections
  if(listen(servSock, MAXPENDING)<0)
    DieWithError("listen() failed");

  // accept incoming connections
  int clientSock;
  struct sockaddr_in clientAddr;
  char buffer[MAX_LENGTH];
  int recvMsgSize;

  int clientAddrLen = sizeof(clientAddr);
  for(;;){
    // wait for a client to connect
    if((clientSock=accept(servSock, (sockaddr*)&clientAddr, &clientAddrLen))<0)
      DieWithError("accept() failed");
    // clientSock is connected to a client


    // BEGIN Handle client
    cout << "Handling client " << inet_ntoa(clientAddr.sin_addr) << endl;
    if((recvMsgSize = recv(clientSock, buffer, MAX_LENGTH, 0)) <0)
      DieWithError("recv() failed");

    cout << "Word in the tubes: " << buffer << endl;
    closesocket(clientSock);

    // END Handle client
  }
}

void DieWithError(char *errorMessage)
{
  fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError());
  exit(1);
}

1 个答案:

答案 0 :(得分:2)

问题在于

servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET

不会像您认为的那样关联。为什么你甚至想写这样的东西,

有什么不对
SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(servSock == INVALID_SOCKET)
    DieWithError("socket() failed");