这就是我所拥有的:
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();
(此代码在循环内)。我想在我将使用变量发送的标头中设置我的服务器主机。这实际上是我试图做的事情:
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 ++的初学者。
答案 0 :(得分:1)
使用std::string
类型的变量,然后使用std::string::c_str()
从中获取可用于调用send
的C字符串。
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);