为什么我不能在C ++中键入要连接的IP

时间:2013-11-19 16:30:50

标签: c++ winsock

所以我有这个代码。在这一行addr.sin_addr.s_addr = inet_addr(ip);我想输入我想要的IP,但是我收到了一个错误。如果不是'ip',我把'127.0.0.1'的错误是:错误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;
}

1 个答案:

答案 0 :(得分:1)

根据错误消息,以下情况应该有效:

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

使用c_str()将其转换为C null终止字符串(char*