为什么 MySQL 客户端不使用我指定的端口?

2022-01-15 00:00:00 mariadb mysql

我正在测试连接问题并测试了我的 JDBC URL 中指定的端口 3307.它起作用了,所以我认为它在那个端口上.然后我看到默认端口是 3306 并尝试了随机端口,它仍然工作.我预计它会失败.为什么命令行忽略端口?

I was testing a connection issue and tested port 3307 as specified in my JDBC URL. It worked, so I assumed it was on that port. Then I saw the default port was 3306 and tried random ports, and it still worked. I expected it to fail. Why is it ignoring the port on the command line?

$ mysql -u root --port 999 -h localhost gb
MariaDB [gb]> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |

$ mysql --version
mysql  Ver 15.1 Distrib 10.1.30-MariaDB, for CYGWIN (i686) using  EditLine wrapper

我也试过 -P 999 并且成功了.

I also tried -P 999 and it worked.

推荐答案

它忽略了端口,因为它使用的是本地套接字连接,而不是 TCP/IP 连接.那是因为主机被指定为 localhost.

It's ignoring the port because it's using a local socket connection, not a TCP/IP connection. That's because the host is specified as localhost.

localhost 在 MySQL 中有特殊的含义.它不会解析为 IP 地址 127.0.0.1(根据我们对该模式的熟悉程度,我们可能会期望它.)

localhost has special meaning in MySQL. It does not resolve to IP address 127.0.0.1 (like we might expect it to, based on our familiarity with that pattern.)

行为记录在 MySQL 参考手册中......

Behavior is documented in MySQL Reference Manual ...

摘自 https://dev.mysql.com/doc/refman/5.7/en/connecting.html

在 Unix 上,MySQL 程序对主机名 localhost 进行特殊处理,与其他基于网络的程序相比,这种方式可能与您所期望的不同.对于到 localhost 的连接,MySQL 程序尝试使用 Unix 套接字文件连接到本地服务器.即使给出 --port 或 -P 选项来指定端口号,也会发生这种情况.要确保客户端与本地服务器建立 TCP/IP 连接,请使用 --host 或 -h 指定主机名值 127.0.0.1,或本地服务器的 IP 地址或名称.您还可以使用 --protocol=TCP 选项显式指定连接协议,即使对于 localhost 也是如此.例如:

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option. For example:

相关文章