bind() 失败并出现 Windows 套接字错误 10038

Posted

技术标签:

【中文标题】bind() 失败并出现 Windows 套接字错误 10038【英文标题】:bind() fails with windows socket error 10038 【发布时间】:2010-05-23 13:23:20 【问题描述】:

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

代码编译,但我得到一个bind() failed: 10038。在msdn上查找错误号(非socket上的socket操作)后,我更改了一些代码

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】:

问题出在

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");

?

【讨论】:

感谢您的帮助!我正在从教程中复制(虽然是手工)。不过,你是对的,这条线看起来很丑。

以上是关于bind() 失败并出现 Windows 套接字错误 10038的主要内容,如果未能解决你的问题,请参考以下文章

调研套接字server bind 失败的原因?——Address already in use

Win8.1升级Windows10出现报错怎么解决

Nginx- 错误:绑定()到 0.0.0.0:80 失败。没有权限

CAsyncSocket create创建套接字失败

在进程退出时释放绑定端口

运行 wamp 3.1.3 Apache 2.4.33 失败并出现 make_sock: could not bind to address [::]:80 NT Kernel and System