PHP Curl, retrieving Server IP Address - php

I'm using PHP CURL to send a request to a server. What do I need to do so the response from server will include that server's IP address?

This can be done with curl, with the advantage of having no other network traffic besides the curl request/response. DNS requests are made by curl to get the ip addresses, which can be found in the verbose report. So:
Turn on CURLOPT_VERBOSE.
Direct CURLOPT_STDERR to a
"php://temp" stream wrapper resource.
Using preg_match_all(), parse the
resource's string content for the ip
address(es).
The responding server addresses will
be in the match array's zero-key
subarray.
The address of the server delivering
the content (assuming a successful
request) can be retrieved with
end(). Any intervening
servers' addresses will also be in
the subarray, in order.
Demo:
$url = 'http://google.com';
$wrapper = fopen('php://temp', 'r+');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $wrapper);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$ips = get_curl_remote_ips($wrapper);
fclose($wrapper);
echo end($ips); // 208.69.36.231
function get_curl_remote_ips($fp)
{
rewind($fp);
$str = fread($fp, 8192);
$regex = '/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/';
if (preg_match_all($regex, $str, $matches)) {
return array_unique($matches[0]); // Array([0] => 74.125.45.100 [2] => 208.69.36.231)
} else {
return false;
}
}

I think you should be able to get the IP address from the server with:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
curl_exec($ch);
$ip = curl_getinfo($ch,CURLINFO_PRIMARY_IP);
curl_close($ch);
echo $ip; // 151.101.129.69

I don't think there is a way to get that IP address directly from curl.
But something like this could do the trick :
First, do the curl request, and use curl_getinfo to get the "real" URL that has been fetched -- this is because the first URL can redirect to another one, and you want the final one :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
$real_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
var_dump($real_url); // http://www.google.fr/
Then, use parse_url to extract the "host" part from that final URL :
$host = parse_url($real_url, PHP_URL_HOST);
var_dump($host); // www.google.fr
And, finally, use gethostbyname to get the IP address that correspond to that host :
$ip = gethostbyname($host);
var_dump($ip); // 209.85.227.99
Well...
That's a solution ^^ It should work in most cases, I suppose -- though I'm not sure you would always get the "correct" result if there is some kind of load-balancing mecanism...

echo '<pre>';
print_r(gethostbynamel($host));
echo '</pre>';
That will give you all the IP addresses associated with the given host name.

AFAIK you can not 'force' the server to send you his IP address in the response. Why not look it up directly? (Check this question/answers for how to do that from php)

I used this one
<?
$hosts = gethostbynamel($hostname);
if (is_array($hosts)) {
echo "Host ".$hostname." resolves to:<br><br>";
foreach ($hosts as $ip) {
echo "IP: ".$ip."<br>";
}
} else {
echo "Host ".$hostname." is not tied to any IP.";
}
?>
from here: http://php.net/manual/en/function.gethostbynamel.php

Related

PHP cURL Received HTTP code 407 from proxy after CONNECT

I have a php curl with proxy problem.
Below is my code:
<?php
$proxylist = file('proxy.txt');
$random_proxy = $proxylist[mt_rand(0,count($proxylist)-1)];
$pinfos = explode(':', $random_proxy);
$proxyipport = $pinfos[0].':'.$pinfos[1];
$proxyuserpwd = $pinfos[2].':'.$pinfos[3];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://google.com');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_PROXY, $proxyipport);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuserpwd);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch).'<br/>';
}
curl_close($ch);
echo $result;
?>
The format of proxies in proxy.txt is ip:port:user:pass and all proxies are working.
The problem is when I used $proxyipport and $proxyuserpwd in CURLOPT_PROXY and CURLOPT_USERPWD, the curl result threw the error Received HTTP code 407 from proxy after CONNECT. However, when I replaced those variables with actual ip:port, user:pass, it worked as normal. I also did an echo of $proxyipport and $proxyuserpwd and it showed me the exact ip:port and user:pass as expected.
Can someone please tell what I did wrong and how to fix that?
Thanks in advance!
Most likely it is the newline \n, so try:
$proxylist = file('proxy.txt', FILE_IGNORE_NEW_LINES);
If it is another hidden character(s) or a Windows format file then with \r you can try:
$pinfos = explode(':', $random_proxy);
$pinfos = array_map('trim', $pinfos);

Sending a JSON array from one machine to another using PHP cURL - How to construct destination URL from destination IP address

I have two vitual machines installed in a VMWare Workstation and they both have different IP address. I want to send a JSON array from one virtual machine to the other. So I am using the PHP cURL library to send the data, and have followed this tutorial. Below is my code snippet. For the sake of this question, let's suppose that AAA.BBB.CCC.DDD is the IP address of the destination host where I want to send the JSON data.
I have two questions:
All I know is the IP address of the destination host. That destination computer does have an XAMPP local server on it. NOW how do I contruct that URL for the destination? Please see the first line in the snippet below, am I making up the URL correctly?
2.When I execute this script on the localhost and meanwhile run Wireshark, three packets appear to be sent to the particular destination IP address. BUT I don't know how to receive the particular JSON data in the destination machine? It will be great if someone can point me to a tutorial for that or give me a hint?
<?php
$url = "http://AAA.BBB.CCC.DDD"; // AAA.BBB.CCC.DDD is replaced by the IP address of destination host.
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'name' => 'Jeremy',
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
My simple test example:
<?php
$url = 'http://localhost/curl-req.php';
$data = array("name" => "Heniek", "age" => "125", "rozmiar" => "M");
$data = json_encode($data);
// Send post data Json format
echo CurlSendPostJson($url,$data);
// send curl post
function CurlSendPostJson($url='http://localhost/curl-req.php',$datajson){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $datajson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($datajson)));
//curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
return $result = curl_exec($ch);
}
?>
<?php
// save belove to: curl-req.php
// GET JSON CONTENT FROM CURL
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
//echo $json = json_decode($jsonStr);
if (!empty($jsonStr)) {
echo $jsonStr;
}
// POST DATA FROM CURL
if (empty($jsonStr)) {
echo serialize($_POST);
}
// GET DATA FROM CURL
if (!empty($_GET)) {
echo serialize($_GET);
}
?>

Geoplugin API Displaying incorrect results

I'm using Geoplugin to retrieve users' current location. Everything works fine except the data is wrong. My Country is Oman but the output is USA.
Note that, I'm not using VPN or Proxy.
Code:
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = unserialize(file_get_contents_curl('http://www.geoplugin.net/php.gp?'.$_SERVER['REMOTE_ADDR']));
$orig_lat = $url["geoplugin_latitude"];
$orig_lon = $url["geoplugin_longitude"];
echo $orig_lat;
echo $orig_lon;
I'm using also cUrl instead of file_get_contents because allow_url_fopen in off in the server.
Output:
41.877602
-87.627197
EDIT:
I figure out that I forget to write ip in the url. http://www.geoplugin.net/php.gp?ip=
Problem SOLVED :)
Using your code returns real coordenates to my location.
Geoplugin uses MaxMind DB to get data, you can check this source.

How to change tor ip each curl_init()

In order to resolve my project, I installed tor and privoxy on my virtual station (Debian).
I found how to use curl and Tor proxy, but I can't change Ip adress at each curl_init().
here is my code:
#!/usr/bin/env php
<?php
function get_url($url)
{
// ensure PHP cURL library is installed
if(function_exists('curl_init'))
{
$timestart=microtime(true);
$ip = '127.0.0.1';
$port = '9050';
$auth = 'rebootip';
$command = 'signal NEWNYM';
$fp = fsockopen($ip,$port,$error_number,$err_string,10);
if(!$fp)
{
echo "ERROR: $error_number : $err_string";
return false;
}
else
{
fwrite($fp,"AUTHENTICATE \"".$auth."\"\n");
$received = fread($fp,512);
fwrite($fp,$command."\n");
$received = fread($fp,512);
}
fclose($fp);
$ch = curl_init();
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050");
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
$response = curl_exec($ch);
$error = curl_error($ch);
print_r($response."\n");
print_r($error."\n");
}
else // PHP cURL library not installed
{
echo 'Please install PHP cURL library';
}
}
echo get_url('http://ipinfo.io/');
is this-I need to change the configuration of "tor" and "privoxy" in order to change ip address ?
thanks in advance :)
To get a different exit node IP address, setup multiple Tor clients listening on port 9050, 9051, ... etc. Then on curl_init, change the proxy port to another available Tor client.
Once you have exhausted your current list of Tor clients, you can restart them to get another exit node. You can even send simple telnet commands directly to your Tor client to change the exit node.

CURLOPT_TIMEOUT , is there "else" function?

<?php
function get_random_proxy()
{
srand ((double)microtime()*1000000);
$f_contents = file ("proxy.txt");
$line = $f_contents[array_rand ($f_contents)];
return $line;
}
$proxy = get_random_proxy();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "example.com");
curl_setopt($ch, CURLOPT_PROXY,$proxy);
curl_setopt($ch, CURLOPT_TIMEOUT ,30);
curl_exec($ch);
curl_close($ch);
?>
curl will close connection if can not connect within the 30 seconds.
as you can see, i'm using proxy list. however, some proxy ips sometimes have problems to connect within the 30 seconds, and curl is closing connection when can not load in 30 seconds.
i wanna try another ip for curl connect if curl timeout reached. right now, curl is closing everything if ip isn't working. i wanna try another ip. well, could you please suggest me a function?
edited for #rubayeet. added new proxy function
You just have to use curl_errno to test if CURLE_OPERATION_TIMEDOUT occured
function get($url, $proxy){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY,$proxy);
curl_setopt($ch, CURLOPT_TIMEOUT ,30);
$response = curl_exec($ch);
curl_close($ch);
return $response
}
$url = 'example.com';
while(true) {
$proxy = get_random_proxy();
$response = get($url, $proxy);
if ($response === False) continue;
else break;
}
//do something with $response
You have to create a new curl session to connect to another proxy. So put a foreach loop around your code and loop through your proxy array.
Also you can use curl_errno() and curl_error() to check for an error (like your timeout).
Maybe it would be useful to set CURLOPT_RETURNTRANSFER and load it into a var to modify or work on it.

Categories