c windows connect() 失败。错误10049

发布于 2024-09-02 06:08:50 字数 5629 浏览 2 评论 0原文

以下两段代码可以编译,但我在客户端收到 connect() failed 错误。 (用 MinGW 编译)。

客户端代码:

// thanks to cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClientWS.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define RCVBUFSIZE 32 // size of receive buffer

void DieWithError(char *errorMessage);

int main(int argc, char* argv[])
{
  int sock;
  struct sockaddr_in echoServAddr;
  unsigned short echoServPort;
  char *servIP;
  char *echoString;
  char echoBuffer[RCVBUFSIZE];
  int echoStringLen;
  int bytesRcvd, totalBytesRcvd;
  WSAData wsaData;

  if((argc < 3) || (argc > 4)){
    fprintf(stderr, "Usage: %s <Sever IP> <Echo Word> [<Echo Port>]\n", argv[0]);
    exit(1);
  }

  if (argc==4)
    echoServPort = atoi(argv[3]); // use given port if any
  else
    echoServPort = 7; // echo is well-known port for echo service

  if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0){ // load winsock 2.0 dll
    fprintf(stderr, "WSAStartup() failed");
    exit(1);
  }

  // create reliable, stream socket using tcp
  if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    DieWithError("socket() failed");

  // construct the server address structure
  memset(&echoServAddr, 0, sizeof(echoServAddr));
  echoServAddr.sin_family = AF_INET;
  echoServAddr.sin_addr.s_addr = inet_addr(servIP); // server IP address
  echoServAddr.sin_port = htons(echoServPort);
  // establish connection to the echo server
  if(connect(sock, (struct sockaddr*)&echoServAddr, sizeof(echoServAddr)) < 0)
    DieWithError("connect() failed");

  echoStringLen = strlen(echoString); // determine input length

  // send the string, includeing the null terminator to the server
  if(send(sock, echoString, echoStringLen, 0)!= echoStringLen)
    DieWithError("send() sent a different number of bytes than expected");

  totalBytesRcvd = 0;
  printf("Received: "); // setup to print the echoed string
  while(totalBytesRcvd < echoStringLen){
    // receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender
    if(bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE-1, 0) <= 0)
      DieWithError("recv() failed or connection closed prematurely");
    totalBytesRcvd += bytesRcvd; // keep tally of total bytes
    echoBuffer[bytesRcvd] = '\0';
    printf("%s", echoBuffer); // print the echo buffer
  }

  printf("\n");
  closesocket(sock);
  WSACleanup(); 

  exit(0);
}

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

服务器代码:

// thanks cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServerWS.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define MAXPENDING 5 // maximum outstanding connection requests
#define RCVBUFSIZE 1000

void DieWithError(char *errorMessage);
void HandleTCPClient(int clntSocket); // tcp client handling function

int main(int argc, char **argv)
{
  int serverSock;
  int clientSock;
  struct sockaddr_in echoServerAddr;
  struct sockaddr_in echoClientAddr;
  unsigned short echoServerPort;
  int clientLen; // length of client address data structure
  WSAData wsaData;

  if (argc!=2){
    fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);
    exit(1);
  }

  echoServerPort = atoi(argv[1]);

  if(WSAStartup(MAKEWORD(2, 0), &wsaData)!=0){
    fprintf(stderr, "WSAStartup() failed");
    exit(1);
  }

  // create socket for incoming connections
  if((serverSock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0)
    DieWithError("socket() failed");

  // construct local address structure
  memset(&echoServerAddr, 0, sizeof(echoServerAddr));
  echoServerAddr.sin_family = AF_INET;
  echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface
  echoServerAddr.sin_port = htons(echoServerPort); // local port

  // bind to the local address
  if(bind(serverSock, 
      (struct sockaddr*)&echoServerAddr, 
      sizeof(echoServerAddr)
      )<0)
    DieWithError("bind() failed");

  // mark the socket so it will listen for incoming connections
  if(listen(serverSock, MAXPENDING)<0)
    DieWithError("listen() failed");

  for (;;){ // run forever
    // set the size of the in-out parameter
    clientLen = sizeof(echoClientAddr);

    // wait for a client to connect
    if((clientSock = accept(serverSock, (struct sockaddr*)&echoClientAddr,
                &clientLen)) < 0)
      DieWithError("accept() failed");

    // clientSock is connected to a client

    printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr));

    HandleTCPClient(clientSock);
  }

  // NOT REACHED
}

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

void HandleTCPClient(int clientSocket)
{
  char echoBuffer[RCVBUFSIZE]; // buffer for echostring
  int recvMsgSize; // size of received message

  // receive message from client
  if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0) <0))
    DieWithError("recv() failed");

  // send received string and receive again until end of transmission
  while(recvMsgSize > 0){
    // echo message back to client
    if(send(clientSocket, echoBuffer, recvMsgSize, 0)!=recvMsgSize)
      DieWithError("send() failed");

    // see if there's more data to receive
    if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0)) <0)
      DieWithError("recv() failed");
  }

  closesocket(clientSocket); // close client socket
}

我该如何解决这个问题?

The following two pieces of code compile, but I get a connect() failed error on the client side. (compiled with MinGW).

Client Code:

// thanks to cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClientWS.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define RCVBUFSIZE 32 // size of receive buffer

void DieWithError(char *errorMessage);

int main(int argc, char* argv[])
{
  int sock;
  struct sockaddr_in echoServAddr;
  unsigned short echoServPort;
  char *servIP;
  char *echoString;
  char echoBuffer[RCVBUFSIZE];
  int echoStringLen;
  int bytesRcvd, totalBytesRcvd;
  WSAData wsaData;

  if((argc < 3) || (argc > 4)){
    fprintf(stderr, "Usage: %s <Sever IP> <Echo Word> [<Echo Port>]\n", argv[0]);
    exit(1);
  }

  if (argc==4)
    echoServPort = atoi(argv[3]); // use given port if any
  else
    echoServPort = 7; // echo is well-known port for echo service

  if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0){ // load winsock 2.0 dll
    fprintf(stderr, "WSAStartup() failed");
    exit(1);
  }

  // create reliable, stream socket using tcp
  if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    DieWithError("socket() failed");

  // construct the server address structure
  memset(&echoServAddr, 0, sizeof(echoServAddr));
  echoServAddr.sin_family = AF_INET;
  echoServAddr.sin_addr.s_addr = inet_addr(servIP); // server IP address
  echoServAddr.sin_port = htons(echoServPort);
  // establish connection to the echo server
  if(connect(sock, (struct sockaddr*)&echoServAddr, sizeof(echoServAddr)) < 0)
    DieWithError("connect() failed");

  echoStringLen = strlen(echoString); // determine input length

  // send the string, includeing the null terminator to the server
  if(send(sock, echoString, echoStringLen, 0)!= echoStringLen)
    DieWithError("send() sent a different number of bytes than expected");

  totalBytesRcvd = 0;
  printf("Received: "); // setup to print the echoed string
  while(totalBytesRcvd < echoStringLen){
    // receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender
    if(bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE-1, 0) <= 0)
      DieWithError("recv() failed or connection closed prematurely");
    totalBytesRcvd += bytesRcvd; // keep tally of total bytes
    echoBuffer[bytesRcvd] = '\0';
    printf("%s", echoBuffer); // print the echo buffer
  }

  printf("\n");
  closesocket(sock);
  WSACleanup(); 

  exit(0);
}

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

Server Code:

// thanks cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServerWS.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define MAXPENDING 5 // maximum outstanding connection requests
#define RCVBUFSIZE 1000

void DieWithError(char *errorMessage);
void HandleTCPClient(int clntSocket); // tcp client handling function

int main(int argc, char **argv)
{
  int serverSock;
  int clientSock;
  struct sockaddr_in echoServerAddr;
  struct sockaddr_in echoClientAddr;
  unsigned short echoServerPort;
  int clientLen; // length of client address data structure
  WSAData wsaData;

  if (argc!=2){
    fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);
    exit(1);
  }

  echoServerPort = atoi(argv[1]);

  if(WSAStartup(MAKEWORD(2, 0), &wsaData)!=0){
    fprintf(stderr, "WSAStartup() failed");
    exit(1);
  }

  // create socket for incoming connections
  if((serverSock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0)
    DieWithError("socket() failed");

  // construct local address structure
  memset(&echoServerAddr, 0, sizeof(echoServerAddr));
  echoServerAddr.sin_family = AF_INET;
  echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface
  echoServerAddr.sin_port = htons(echoServerPort); // local port

  // bind to the local address
  if(bind(serverSock, 
      (struct sockaddr*)&echoServerAddr, 
      sizeof(echoServerAddr)
      )<0)
    DieWithError("bind() failed");

  // mark the socket so it will listen for incoming connections
  if(listen(serverSock, MAXPENDING)<0)
    DieWithError("listen() failed");

  for (;;){ // run forever
    // set the size of the in-out parameter
    clientLen = sizeof(echoClientAddr);

    // wait for a client to connect
    if((clientSock = accept(serverSock, (struct sockaddr*)&echoClientAddr,
                &clientLen)) < 0)
      DieWithError("accept() failed");

    // clientSock is connected to a client

    printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr));

    HandleTCPClient(clientSock);
  }

  // NOT REACHED
}

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

void HandleTCPClient(int clientSocket)
{
  char echoBuffer[RCVBUFSIZE]; // buffer for echostring
  int recvMsgSize; // size of received message

  // receive message from client
  if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0) <0))
    DieWithError("recv() failed");

  // send received string and receive again until end of transmission
  while(recvMsgSize > 0){
    // echo message back to client
    if(send(clientSocket, echoBuffer, recvMsgSize, 0)!=recvMsgSize)
      DieWithError("send() failed");

    // see if there's more data to receive
    if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0)) <0)
      DieWithError("recv() failed");
  }

  closesocket(clientSocket); // close client socket
}

How can I fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泛泛之交 2024-09-09 06:08:50

您没有初始化 servIP:

servIP = argv[1];

我认为您确实需要熟悉调试器,因为您应该能够使用调试器在几秒钟内发现此类错误。

You don't initialize servIP:

servIP = argv[1];

I think you really need to become familiar with your debugger, because you should have been able to spot this kind of mistake in a few seconds with a debugger.

离线来电— 2024-09-09 06:08:50

问题出在客户端。

  1. servIP 未分配给正确的值。您可以使用
    servIP = argv[1];
    在加载winsock2 dll之前。

  2. 这是recv(...)返回0的正常情况。这意味着连接已关闭。

The problem lies within the client-side.

  1. servIP was not assigned to the proper value. You can use
    servIP = argv[1];
    before loading winsock2 dll.

  2. it is a normal case for recv(...) returning 0. It means the connection is closed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文