After resolving and calling host via ipv6 with curl, next ipv4 request fails and vice versa

Posted by Ranty on Stack Overflow See other posts from Stack Overflow or by Ranty
Published on 2012-10-28T10:55:53Z Indexed on 2012/10/28 11:00 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

I need to request the same host with different methods (using IPv4 and IPv6) from the same script. First request is always successful (no matter IPv4 or IPv6), but the second always fails with curl error 45 (Couldn't bind to IP).

I'm using the following curl config:

function v4_google()
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1');
    curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/search?q=Moon');
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_INTERFACE, 'My IPv4 address');
    $c = curl_exec($ch);
    $result = !curl_errno($ch) ? 'Success' : '<b>' . curl_error($ch) . '; #' . curl_errno($ch) . '</b>';
    echo '<p>v4_google:<br>Response length: ' . mb_strlen($c) . '<br>Result: ' . $result . '</p>';
    curl_close($ch);
}
function v6_google()
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1');
    curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/search?q=Moon');
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
    curl_setopt($ch, CURLOPT_INTERFACE, 'My IPv6 address');
    $c = curl_exec($ch);
    $result = !curl_errno($ch) ? 'Success' : '<b>' . curl_error($ch) . '; #' . curl_errno($ch) . '</b>';
    echo '<p>v6_google:<br>Response length: ' . mb_strlen($c) . '<br>Result: ' . $result . '</p>';
    curl_close($ch);
}

v6_google();
v4_google();

So long story short, if I query v6_google(); first, then all consecutive calls of v4_google(); are failing with the curl error 45 (Couldn't bind to IP). And vice versa.

As you can see, I separated code into different functions and added CURLOPT_FORBID_REUSE and CURLOPT_FRESH_CONNECT plus curl_close($ch), but it didn't help at all.

It looks like curl is caching the resolving method of every host you request, and even if you specify another resolving method the next time you call that host, the cached one is used instead.

I would appreciate any help with this issue.

© Stack Overflow or respective owner

Related posts about php

Related posts about curl