gpt4 book ai didi

c++ - 通过传递参数进行字符串连接

转载 作者:行者123 更新时间:2023-11-28 05:55:33 27 4
gpt4 key购买 nike

这是我的:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
}
SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("myserverip");
SOCKADDR_IN SockAddr;
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
// system("pause");
}
cout << "Connected.\n";
send(Socket,"GET / HTTP/1.1\r\nHost: myserverip\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: myserverip\r\nConnection: close\r\n\r\n"),0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();

(此代码在循环内)。我想在我将使用变量发送的 header 中设置我的服务器主机。这实际上是我试图做的:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
}
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname(myhost);
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
return 1;
}
send(Socket, "GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();

这段代码也在一个循环中。全局变量声明如下:

string myhost;

但我无法让它工作,尤其是在这一行:

send(Socket, "GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: " + myhost + "\r\nConnection: close\r\n\r\n"), 0);

我该如何解决这个问题?我是 C++ 的初学者。

最佳答案

使用 std::string 类型的变量,然后使用 std::string::c_str() 从中获取您可以在其中使用的 C 字符串对 send 的调用。

std::string str = "GET / HTTP/1.1\r\nHost: ";
str += myhost;
str += "\r\nConnection: close\r\n\r\n";

send(Socket, str.c_str(), str.size(), 0);

关于c++ - 通过传递参数进行字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34234285/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com