【问题标题】:Why is Connect() returning a negative value?为什么 Connect() 返回负值?
【发布时间】:2020-04-01 03:41:55
【问题描述】:
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#include <ctype.h>
#include<string.h>
#include<strings.h>

#define MY_PORT     8989 //defining the port for the socket
#define MAXBUF      256



int main(int argc , char *argv[])
{
    //char str[MAXBUF];
    int a;
    WSADATA wsa;

    SOCKET sockfd , clientfd; //SOCKET is a data type. We initialize two variables of the data type Socket here
    struct sockaddr_in self; //structure for the family,port and IP address of the socket (Socket descriptors)
    char buffer[MAXBUF]; // this is a character array that will receive the message from the client and we will use this to manipulate
    //char message[MAXBUF];
    printf("\nInitialising Winsock...");


    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) //WSASTARUP is used to tell windows to get ready for a connection and if it returns a value 0, windows is ready
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1;
    }


    printf("Initialised.\n");

    /*---create streaming socket---*/
    if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) //socket is created using a function called socket
                                                        //using AF_INET means that we are using TCP/IP family
                                                          //the if statement here checks whether or not the value returned by the socket is negative or not. If it is negative that means there is some sort of an error
    {
        perror("Socket");
        exit(errno);
    }
        printf("Socket created.\n");
        self.sin_family = AF_INET;
        self.sin_port = htons(MY_PORT);
        self.sin_addr.s_addr = htonl(INADDR_ANY);
        memset(&self,'\0', sizeof(self));
    /*The connect function below is used to establish a connection between the client and the server*/
    if (connect(sockfd, (struct sockaddr*)&self, sizeof(self)) <0)
        {
        printf("connection with the server failed...\n");
        exit(0);
        }
        else
        printf("connected to the server..\n");

        printf("Please enter message: ");
        memset(buffer, 0, sizeof (buffer));
        fgets(buffer, MAXBUF, stdin); //fgets is used here to get whatever is inside the buffer
        while (1)
        {
        /*struct sockaddr_in client_addr;
        int addrlen=sizeof(client_addr);*/

        /*---accept a connection (creating a data pipe)---*/

        a=  write(sockfd, buffer, sizeof(buffer));
        if(a<0){
        printf("Error");
            }
        // a= recv(clientfd, buffer, MAXBUF, 0);
        //accept(clientfd, (struct sockaddr*)&client_addr, &addrlen);

        a= read(sockfd, buffer, sizeof(buffer));
        if(a<0){
        printf("Error");
      }
        if (strncmp("QUIT", buffer, 4) == 0) {
            printf("Server Exit...\n");
            break;

        }
        }

    close(sockfd); //close the sockfd
    WSACleanup(); // windows socket is cleaned up
    return 0;
}


代码工作得很好,但由于某种原因,我无法将我的头脑围绕连接函数继续返回一个负值,或者至少一个不为零的值。我与此客户端一起使用的服务器适用于其他客户端,所以我知道它没有任何问题。

您的帮助将不胜感激。

【问题讨论】:

  • 来自the documentation: "如果没有发生错误,则connect返回零,否则返回SOCKET_ERROR,可以通过调用WSAGetLastError获取特定的错误代码 。”。因此,请帮自己一个忙,并检查错误的详细信息。要么这已经导致你的问题得到解释,要么你至少应该在你的问题中包含这些错误细节。
  • connect 函数在出错时返回一个“负”值,正如文档所述。
  • 在相应结构中设置值之前将调用移至memset
  • 另外花点时间缩进你的代码...
  • 通过使用 WSAGetLastError,它给了我错误代码 10049,而且我已经移动了 memset

标签: c sockets client client-server


【解决方案1】:
    self.sin_family = AF_INET;
    self.sin_port = htons(MY_PORT);
    self.sin_addr.s_addr = htonl(INADDR_ANY);

    memset(&self,'\0', sizeof(self));

在这段代码中,您设置了self 的所有值,然后您只需用memset 清除self。我很确定这没有任何意义,很可能是您看到的错误的原因,即没有为 connect 提供有用的参数。

即使没有这个错误的memset,代码也没有多大意义:您正在尝试连接到INADDR_ANY,但没有这样的IP 地址可以连接。 INADDR_ANY 意味着在服务器端监听机器的每个地址 - 在客户端它不能被使用,而是必须使用真实的 IP 地址,比如 127.0.0.1 用于本地主机。

【讨论】:

  • 不,不是,我移动它仍然给了我同样的错误。我认为这与地址有关,但我完全确定
  • @user66581:我很确定这至少是问题的一部分,但可能还有更多问题。正如我在评论中已经说过的:使用 WSAGetLastError 获取详细错误以获取有关连接失败原因的更多信息。
  • 是的,我确实这样做了,它给了我一个错误代码 10049,我觉得这与地址有关
  • @user66581:我刚刚看到您的代码有更多问题,请参阅更新的答案。
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2021-12-09
  • 2017-11-16
  • 1970-01-01
  • 2019-04-28
相关资源
最近更新 更多