PHP and PDO: connecting to MySQL using an IPv6 address

I want to connect to a remote instance of MySQL (Google Cloud SQL one) using my IPv6 address.

I am using PHP PDO as follows:

$db = new \PDO('mysql:host=<ipv6-address>;port=3306;dbname=<database-name>', '<username>', '<password>' ); 

But it always fails with the following exception message:

PDOException: SQLSTATE [HY000] [2002] No host route

From the terminal, I can connect to the MySQL instance without any problems, for example:

 mysql --host=<ipv6-address> --user=<username> --<password> 

Any help would be really appreciated.

thanks

+6
source share
3 answers

In case someone else is facing the same problem, and to keep them for 2 hours through a PHP source, the MySQL IPv6 PDO connections work if you put square brackets around the address.

See: https://github.com/php/php-src/blob/master/main/streams/xp_socket.c#L568

eg.

 $pdo = new PDO("mysql:host=[1234:5678::42];port=3306;dbname=foo", ...); 
+4
source

Reading this https://www.saotn.org/php-mysql-and-ipv6-still-slow/ gives the following idea:

Knowing that, as a rule, IPv6 takes precedence over IPv4 (which is configurable), users remain with a slow response to the website and database operations, only because the connection to the IPv6 address in PHP is denied and the connection is denied, it is not processed right, which makes the transition to IPv4 slow. Mysql.connect_timeout seconds required

Note: the source seems reliable

Also, it is useful to read: http://dev.mysql.com/worklog/task/?id=798

MySQL support must be added to work on IPv6
("Internet Protocol 6").
It means:
- Users can connect to IPv6. this is partly a problem with the connector .
- storage of information about user addresses, for example. in mysql.user, maybe in IPv6 format
- the proposed new CIDR and INET data types allow IPv6 format as described in WL # 2037 "Add CIDR and INET Data Types"
- functions like inet_ntoa () need to be reviewed

+3
source

Try using this for your PDO connection and see if it works.

 $dbh = new PDO('mysql:host=<ipv6-address>;port=<port>;dbname=<dbname>', <dbusername>, <dbpassword>); 

In case of failure, you can better use try...catch to get exactly the error

 <?php try { $dbh = new PDO('mysql:host=<ipv6-address>;port=<port>;dbname=<dbname>', <dbusername>, <dbpassword>); } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?> 
0
source

Source: https://habr.com/ru/post/987751/


All Articles