Winsock 服务器和客户端示例:未在此范围内声明"getaddrinfo"

Winsock Server And Client Example: "getaddrinfo" was not declared in this scope

本文关键字:范围内 声明 getaddrinfo 服务器 客户端 Winsock      更新时间:2023-10-16

我正在尝试用一个简单的服务器和客户端在C++中联网,从一些Winsock示例开始。

每当我试图用代码::块编译服务器时,我都会收到以下错误:

||=== Build: Debug in Server Test (compiler: GNU GCC Compiler) ===|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|12|warning: ignoring #pragma comment  [-Wunknown-pragmas]|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp||In function 'int main()':|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|47|error: 'getaddrinfo' was not declared in this scope|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|57|warning: format '%ld' expects argument of type 'long int', but argument 2 has type 'int' [-Wformat]|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|58|error: 'freeaddrinfo' was not declared in this scope|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|67|error: 'freeaddrinfo' was not declared in this scope|
C:Users****DesktopProgrammingCodeBlocks ProjectsServer Testmain.cpp|73|error: 'freeaddrinfo' was not declared in this scope|
||=== Build failed: 4 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

我已经尝试过这个问题的解决方案,但是,这导致了36个错误。

我对客户端代码也有同样的问题。

服务器代码:

#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(void)
{
    WSADATA wsaData;
    int iResult;
    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL;
    struct addrinfo hints;
    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %dn", iResult);
        return 1;
    }
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;
    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %dn", iResult);
        WSACleanup();
        return 1;
    }
    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ldn", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %dn", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    freeaddrinfo(result);
    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %dn", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %dn", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    // No longer need server socket
    closesocket(ListenSocket);
    // Receive until the peer shuts down the connection
    do {
        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %dn", iResult);
        // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed with error: %dn", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %dn", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...n");
        else  {
            printf("recv failed with error: %dn", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }
    } while (iResult > 0);
    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %dn", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }
    // cleanup
    closesocket(ClientSocket);
    WSACleanup();
    return 0;
}

以防有人仍在与此问题作斗争。你所要做的就是:

  • 在代码开头定义_WIN32_WINNT,如下所示:#define _WIN32_WINNT 0x501(由ws2tcpip.h使用)
  • 按此方式编译:g++ prog.c -o prog -lws2_32

这些步骤是在代码、服务器和客户端上执行的。

希望这能有所帮助。

我在这台机器上没有VS,但尝试在windows.h之前导入winsock2.h。

我确实有带有gcc的Cygwin,并在命令行编译了源代码:

gcc服务器.cpp-lws2_32服务器.exe

似乎有效:

telnet 127.0.0.1 27015