From 7c8c096a729dc3489172eca45f931902c1563b4e Mon Sep 17 00:00:00 2001 From: Pavel Abalihin Date: Wed, 20 Aug 2014 13:01:36 +0400 Subject: [PATCH] IPv6 support --- include/emysql.hrl | 5 ++++- src/emysql_conn.erl | 18 +++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/include/emysql.hrl b/include/emysql.hrl index 1320289f..c50a8b78 100644 --- a/include/emysql.hrl +++ b/include/emysql.hrl @@ -125,7 +125,10 @@ -define(CONNECT_WITH_DB, 8). -define(CONN_TEST_PERIOD, 28000). -define(TCP_RECV_BUFFER, 8192). - +-define(SOCKET_OPTIONS, [binary, + {packet, raw}, + {active, false}, + {recbuf, ?TCP_RECV_BUFFER}]). %% MYSQL TYPES -define(FIELD_TYPE_DECIMAL, 16#00). diff --git a/src/emysql_conn.erl b/src/emysql_conn.erl index 01a5c74b..edf7626f 100644 --- a/src/emysql_conn.erl +++ b/src/emysql_conn.erl @@ -187,7 +187,8 @@ open_connection(#pool{pool_id=PoolId, host=Host, port=Port, user=User, start_cmds=StartCmds, connect_timeout=ConnectTimeout} = Pool) -> %-% io:format("~p open connection for pool ~p host ~p port ~p user ~p base ~p~n", [self(), PoolId, Host, Port, User, Database]), %-% io:format("~p open connection: ... connect ... ~n", [self()]), - case gen_tcp:connect(Host, Port, [binary, {packet, raw}, {active, false}, {recbuf, ?TCP_RECV_BUFFER}], ConnectTimeout) of + IpFamily = host_ipfamily(Host), + case gen_tcp:connect(Host, Port, [IpFamily | ?SOCKET_OPTIONS], ConnectTimeout) of {ok, Sock} -> #greeting { server_version = Version, @@ -220,6 +221,21 @@ open_connection(#pool{pool_id=PoolId, host=Host, port=Port, user=User, exit({failed_to_connect_to_database, Reason}) end. +host_ipfamily(Host) -> + case inet_parse:address(Host) of + {ok, {_, _, _, _, _, _, _, _}} -> inet6; + {ok, {_, _, _, _}} -> inet; + _ -> + case inet:getaddr(Host, inet6) of + {ok, _} -> inet6; + _ -> + case inet:getaddr(Host, inet) of + {ok, _} -> inet; + {error, Reason} -> exit(Reason) + end + end + end. + handshake(Sock, User, Password) -> case emysql_auth:handshake(Sock, User, Password) of {ok, #greeting{} = G} -> G;