为什么我无法在 C++ 中键入要连接的 IP

Why can't I type the IP I want to connect to in C++

本文关键字:连接 IP C++ 为什么      更新时间:2023-10-16

所以我有这个代码。在这行addr.sin_addr.s_addr = inet_addr(ip);上,我想输入一个我想要的IP,但我得到了一个错误。如果我输入"127.0.0.1"而不是"ip",则它有效。错误为:错误C2664:"inet_addr":无法将参数1从"std::string"转换为"const char*"

谢谢!

#pragma comment(lib, "Ws2_32.lib")
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
SOCKADDR_IN addr;
SOCKET sConnect;
// For this we need to send two information at one time:
// 1. The main message
// 2. The ID
// To send more than one information I will use a struct
string G;
string ip;
struct Buffer
{    
        int ID;
        char Message[256];
};    
int ClientThread()
{    
        Buffer sbuffer;
    char buffer[sizeof(sbuffer)] = {0};
    for(;; Sleep(10))
    {
        // The server will send a struct to the client
        // containing message and ID
        // But send only accepts a char as buffer parameter
        // so here we need to recv a char buffer and then
        // we copy the content of this buffer to our struct
        if(recv(sConnect, buffer, sizeof(sbuffer), NULL))
        {
            memcpy(&sbuffer, buffer, sizeof(sbuffer));
            cout << G << " - " << sbuffer.Message << endl;
        }
    }
    return 0;
}    
int main()
{    
        system("cls");
    int RetVal = 0;
        WSAData wsaData;
    WORD DllVersion = MAKEWORD(2,1);
    RetVal = WSAStartup(DllVersion, &wsaData);
    if(RetVal != 0)
    {
        MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
        exit(1);
    }
    sConnect = socket(AF_INET, SOCK_STREAM, NULL);
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port        = htons(1234);
    addr.sin_family      = AF_INET;
        cout << "Connect to (IP): " << endl;
                cin >> ip;
    RetVal = connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
    if(RetVal != 0)
    {
        MessageBoxA(NULL, "Could not connect to server", "Error", MB_OK | MB_I CONERROR);
        main();
    }
    else
    {
        cout << "Nickname: " << endl;
        cin >> G;
        cout << "Welcome, " << G << endl;

        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) ClientThread, NULL, NULL, NULL);
        for(;; Sleep(10))
        {
            char* buffer = new char[256];
            ZeroMemory(buffer, 256);
            cin >> buffer;
            getchar();
            send(sConnect, buffer, 256, NULL);
        }
    }
    return 0;
}

根据错误消息,以下内容应该有效:

addr.sin_addr.s_addr = inet_addr(ip.c_str());

使用c_str()将其转换为以C null结尾的字符串(char*