Reputation: 3
This is what I have:
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();
(This code is inside a loop). I would like to set my server-host in the header I'll send by using a variable. That's actually what I tried to do:
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();
This code also is inside a loop. The global variable is declared like this:
string myhost;
But I can't get it to work, especially on this line:
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);
How can I fix this? I am a beginner on C++.
Upvotes: 0
Views: 48
Reputation: 206727
Use a variable of type std::string
and then use std::string::c_str()
to get the C string from it that you can use in the call to 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);
Upvotes: 1