为什么我无法在 C++ 中键入要连接的 IP
Why can't I type the IP I want to connect to in C++
所以我有这个代码。在这行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*
)
相关文章:
- 为什么 WinInet 在通过 FQDN 连接时无法通过协商自动进行身份验证,但如果通过 IP 连接则成功?
- C++ Winsock2 客户端未通过远程 IP 连接到服务器
- 使用 IP 帮助程序的 Windows 中活动 UDP 连接的远程地址
- 如何将请求的客户端连接的 IP 与 QTcpSocket 类中识别的 IP 之一进行比较?
- gRPC C++尝试在无法访问的 IP 上连接通道时阻止客户端
- TCP/IP 客户端是否可以连接到无法访问的 IP
- 服务器和客户端都在PC上运行.客户端可以使用PC的IP连接到服务器
- 如何从活动的 udp 连接获取远程 IP 地址和端口
- 使用静态IP地址时,ESP32 httpclient连接拒绝了
- 如何获取其他人可以使用的IP来连接到我的c 中的套接字构建
- 如何在我当前连接的网络中获取本地 IP 地址?
- 获取传入连接的源 IP 地址
- 唯一标识UDP连接-来自同一IP的多个连接
- c++winsock客户端无法使用主机IP的文本框进行连接
- 套接字连接到不存在的ip地址上的端口
- 为什么我无法在 C++ 中键入要连接的 IP
- 提升连接后从TCP服务器访问TCP客户端IP地址+端口
- 连接到外部 IP 失败
- 如何在接受C++中的连接之前获取客户端 IP 地址
- 在接受连接C++之前获取套接字的 IP 地址