我无法从另一台计算机访问Winsock服务器(但localhost可以工作)

时间:2019-07-09 04:09:10

标签: c++ linux sockets winsock winsock2

我无法从另一台计算机连接到我的Winsock服务器(tcp / ip),但可以使用腻子在本地主机上连接。我使用的机器正在运行linux,并且正在使用腻子连接到服务器。我不知道是因为我的计算机正在运行linux还是因为我的代码出错而无法连接,所以需要您的帮助。

Server.cpp

#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <string>

#pragma comment(lib, "ws2_32.lib")

int main()
{
    std::cout << "--- Tcp/ip Server ---" << std::endl;
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);

    SOCKET server = socket(AF_INET, SOCK_STREAM, 0);
    if (server == INVALID_SOCKET)
    {
        std::cout << "error in SOCKET(): "<< WSAGetLastError() << std::endl;
        WSACleanup();
    }
    sockaddr_in s;
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = INADDR_ANY;
    s.sin_port = htons(52000);

    // bind
    if (bind(server, (sockaddr*)&s, sizeof(s)) == SOCKET_ERROR)
    {
        std::cout << "Error: bind()" << std::endl;
    }
    //listen
    if (listen(server, SOMAXCONN) == SOCKET_ERROR)
    {
        std::cout << "Error in listen(): " << WSAGetLastError() << std::endl;
        WSACleanup();
    }
    sockaddr_in from;
    int fromlen = sizeof(from);
    // accept
    SOCKET client = accept(server, (SOCKADDR*)&from, &fromlen);
    if (client == INVALID_SOCKET)
    {
        std::cout << "Error in accept(): " << WSAGetLastError << std::endl;
        WSACleanup();
    }
    else
    {

        char clientIp[17];
        if (inet_ntop(AF_INET, &from.sin_addr, clientIp, 17) == NULL)
        {
            std::cout << "Can't get the client's ip: " << WSAGetLastError() << std::endl;
        }

        std::cout << "ip connected: " << clientIp << std::endl;
    }
    char recvbuf[512];
    do
    {
        int iResult = recv(client, recvbuf, 512, 0);
        if (iResult > 0)
        {
            send(client, recvbuf, iResult, 0);
        }


    } while (true);
    return 0;
}

0 个答案:

没有答案