I have a C++ console app that uses wininet.h to go out to a URL, and download the contents of a web page.
The contents are usually just a single IP address. It goes here: http://www.whatismyip.com/automation/n09230945.asp
Everything works great.
Then I decided to create my own IP checker in PHP, using the following code:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
header("Cache-Control: private");
header("Content-Type: text/html");
echo $ip;
?>
This looks correct in the browser, identical whatismyip.com’s results, but the C++ program just adds bunch of junk after the IP, then repeats the IP half cut off, and then adds more junk.
What is causing this? I tried analyzing the headers, but I can’t spot the difference.
Also, I tried putting a plain txt file on to the server, and the C++ program reads it perfect.
I also tried changing my headers to both plain/text and text/plain. Same result.
Thank you for your help!
Edit: Here’s a portion of the C++ code:
HINTERNET OpenAddress = InternetOpenUrl(connect,"http://www...", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0);
char DataReceived[16] = " ";
DWORD NumberOfBytesRead = 0;
while (InternetReadFile(OpenAddress, DataReceived, 16, &NumberOfBytesRead) && NumberOfBytesRead)
{
cout << DataReceived;
}
coutwill expect a string to be null-terminated. Because you’re just reading bytes into a buffer, and not null-terminating them at the end,coutwill carry on past the end of the bytes you’ve read and just carry on dumping memory out until it hits a null pointer or memory protection kicks in.With your code, what’s happening is this, at a guess:
coutwith DataReceived. This is a char array, andcouttherefore expects it to be a null-terminated string. It outputs every character from the start of the buffer, right past “127.0.01” and onwards until it finds a 0 in memory.Don’t know anything about
InternetReadFile(), but I’d guess an approach like this should work if you’re only grabbing a single line with an IP address in it:But fundamentally, I think the main problem you’re having is in confusing a buffer that’s just a bunch of bytes with a nice friendly null-terminated string, and you should understand that, and maybe look for some existing examples of using InternetReadFile with that in mind to see how they work, and therefore what you need to do.