11

With the following code I can connect to mysql: mysql_connect("localhost","username","");

But if I change localhost to 127.0.0.1 I get the following error:

Can't connect to MySQL server on '127.0.0.1' (13)

Why doesn't it work with 127.0.0.1?

user16948
  • 4,801
  • 10
  • 30
  • 41

5 Answers5

20

localhost is special cased and uses UNIX sockets instead of TCP/IP. 127.0.0.1 doesn't get that special handling.

See the documentation:

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.

If it doesn't work when you use TCP/IP then the database probably isn't listening on the network. This is generally a good thing as it enhances security (not that listening on 127.0.0.1 exposes any problems, but listening on all interfaces gives more opportunity for attacks).

If you really want to allow connections via the network, then see skip-networking.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

have you got an entry in your hosts file mapping 127.0.0.7 to localhost?

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
0

Do you have more than 1 mysql servers installed/running on your system? If so, please specify the port number of the mysql server you are trying to access like 127.0.0.1:3306,127.0.0.1:8889 etc.

If you do not know whether there are any other mysql server instances running on your system also, please specify the port.

ilight
  • 1,622
  • 2
  • 22
  • 44
  • Does running a second instance of MySQL prevent the first from running on the default port now? – Quentin Apr 27 '12 at 09:35
  • No, it does not prevent from running but it may be unable to access the mysql server without mentioning the port number even when it is running on default port when more than 1 instance is running – ilight Apr 27 '12 at 09:39
0

You will be able to access it when you add the privileges for 'root'@'127.0.0.1' in the "USER_PRIVILEGES" table in the "information_schema" database

Prabhuram
  • 1,268
  • 9
  • 15
0

You might also try disabling SELINUX

Ben
  • 197
  • 1
  • 11