服务器和客户端都在PC上运行。客户端可以使用PC的IP连接到服务器吗?

时间:2019-07-07 12:08:34

标签: c++ networking

我是网络编程的新手,所以这困扰了我好几天。

我写了2个应用程序:一个是服务器,一个是客户端。

我希望他们这样做:当我为客户端提供IP地址时,客户端将使用提供的IP连接到计算机上的服务器。

我通过在PC上打开服务器和客户端,并输入回送地址(127.0.0.1)进行了测试。客户端连接到服务器很好(而且我什至可以互相发送短信)。

所以我进一步尝试了。我用我的IP(113.20.98.124)进行了搜索,然后将其提供给我的客户。我希望客户端也可以连接到服务器,但这没有发生。客户端终止,并说连接超时(WSAETIMEDOUT 10060)。

我想问的是:为什么我不能使用IP告诉客户端连接到我的服务器?那甚至是东西吗?

这是我的服务器和客户端代码(以防我做错了):

(我在Windows上使用VS2017编码)

客户:

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


//The port which will be used to connect to server
#define PORT "7777"


std::string getIPAddress()
{
    std::string out;
    std::cout << "IP/Domain to connect to: ";
    std::cin >> out;
    std::cin.ignore();
    return out;
}

//Print out error code and exit the program in case something goes wrong
void failure_exit(std::string message, int exitVal)
{
    std::cerr << message
        << " Error code: " << WSAGetLastError() << " \n";
    WSACleanup();
    std::cin.get();
    exit(exitVal);
}



int main(int argc, char *argv[])
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(1, 0), &wsaData) != 0)
        failure_exit("WSAStartup failed!", 1);


    addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC; //AF_INET or AF_INET6 are totally fine
    hints.ai_socktype = SOCK_STREAM; //TCP connection


    //Get the IP from user
    std::string IPconnect = getIPAddress();


    //A pointer to a linked list of juicy results we can use 
    addrinfo *result(nullptr);

    //Prepare the addrinfo for a connecting socket
    if (getaddrinfo(IPconnect.c_str(), PORT, &hints, &result) != 0)
        failure_exit("getaddrinfo failed!", 2);


/*PREPARING A SOCKET*/
    SOCKET sockfd;
    //A pointer to one of the addrinfos from result, which is a usable one
    //'chosen' will also be used in connect() call
    addrinfo *chosen(result);
    //Run through the results got from getaddrinfo and pick the first usable addrinfo
    for (; chosen != nullptr; chosen = chosen->ai_next)
    {
        //see if sockfd is legit to use
        if ((sockfd = socket(chosen->ai_family, chosen->ai_socktype, chosen->ai_protocol)) != -1)
            break;
    }

    freeaddrinfo(result);

    //Socket preparation failed
    if (sockfd<=0)
        failure_exit("Socket preparation failed!", 3);


/*CONNECT!*/
    std::cout << "Connecting... 20 seconds until timed out.\n";

    if (connect(sockfd, chosen->ai_addr, chosen->ai_addrlen) != 0)
        failure_exit("Failed to connect!", 4);

    std::cout << "Connected!\n";

    WSACleanup();
    std::cin.get();
    return 0;
}

服务器:

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


//The port which this server will be using 
//to listen to incoming connections
#define PORT "7777"

//Limits how many pending connections
//can be queued up
#define BACKLOG 10


void failure_exit(std::string message, int exitVal)
{
    std::cerr << message
        << " Error code: " << WSAGetLastError() << " \n";
    WSACleanup();
    std::cin.get();
    exit(exitVal);
}


int main(int argc, char* argv[])
{
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(1, 0), &wsa) != 0)
        failure_exit("WSAStartup failed!", 1);


    addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    //IPv4 or IPv6 are both Ok
    hints.ai_family = AF_INET;
    //This addrinfo will be used for binding
    hints.ai_flags = AI_PASSIVE;
    //TCP connection
    hints.ai_socktype = SOCK_STREAM;


    addrinfo *result;
    if (getaddrinfo(NULL, PORT, &hints, &result) != 0)
        failure_exit("getaddrinfo failed!", 3);


//PREPARE A SOCKET
    SOCKET sockfd(0);

    //The usable addrinfo will be pointed to by 'chosen'
    addrinfo *chosen(result);

    //Loop through the results to find a suitable one
    for (; chosen != nullptr; chosen = chosen->ai_next)
    {
        sockfd = socket(chosen->ai_family, chosen->ai_socktype, chosen->ai_protocol);
        //Stop at the first usable
        if (sockfd != -1)
            break;
    }
    freeaddrinfo(result);

    //Check for preparation failure
    if (sockfd <= 0)
        failure_exit("Socket preparation failed!", 4);


    //Bind the socket above to my chosen PORT
    if (bind(sockfd, chosen->ai_addr, chosen->ai_addrlen) == -1)
        failure_exit("Binding failed!", 5);


    //Start listening for incoming connections
    if (listen(sockfd, BACKLOG) == -1)
        failure_exit("Listening failed!", 6);


    //The new socket to be returned by accept()
    SOCKET newfd;

    sockaddr_storage newConnection;
    socklen_t newlength(sizeof(newConnection));

    std::cout << "Anyone?\n";

    //Accept a pending connection
    if ((newfd = accept(sockfd, reinterpret_cast<sockaddr*>(&newConnection), &newlength)) == -1)
        failure_exit("Accepting connection failed!", 7);

    std::cout << "Connection accepted!\n";

    WSACleanup();
    std::cin.get();
    return 0;
}

我从网络上学到的任何东西都来自http://beej.us/guide/

1 个答案:

答案 0 :(得分:2)

当您用Google搜索IP时,便获得了外界所看到的公共IP。如果您的PC是直接直接连接到Internet调制解调器,则该IP属于您的PC。但是,如果您的PC位于网络路由器的后面(在如今的家庭中有许多连接Internet的设备非常普遍),则该IP属于您的网络路由器,而不属于您的PC。

您的服务器应用程序只能侦听直接分配给运行它的PC的本地/ LAN IP。如果该PC在网络路由器后面运行,它将无法监听路由器的公共IP。

您的服务器代码以某种方式绑定其侦听套接字,以使其侦听分配给正在运行的PC的所有可用IPv4 IP。要发现这些IP实际上是什么,可以使用Windows的命令行ipconfig工具。或者,您可以在服务器代码中使用GetAdaptersInfo()GetAdaptersAddresses() API。

如果客户端与服务器应用程序在同一PC /网络上运行,则它可以直接连接到服务器正在侦听的任何本地/ LAN IP。但是,如果客户端在其他网络上运行(即,在Internet上的另一台PC上),则需要连接到您的公共IP。并且在该公共IP属于网络路由器的情况下,需要将路由器配置为将给定<PublicIP>:<PublicPort>上的入站连接转发到服务器PC的<LanIP:LanPort>(即,从{{1}转发) },例如113.20.98.124:777,或实际上分配给服务器PC的任何IP。