Home > Article > Backend Development > The difference between mysql_connect localhost and 127.0.0.1 (network layer explanation), _PHP tutorial
connects.php
Copy code The code is as follows:
mysql_connect('127.0.0.1','root','zzzizzz1');
mysql_connect('localhost','root','zzzizzz1');
Use strace to get system calls:
Copy code The code is as follows:
strace php connects.php 2>&1 | grep connect
#127.0.0.1 -> internet socket
connect(3, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress)
#localhost -> unix domain socket
connect(7, {sa_family=AF_FILE, path="/var/run/mysqld/mysqld.sock"}, 110) = 0
Socket was originally designed for network communication, but later an IPC mechanism was developed based on the Socket framework, which is UNIX Domain Socket.
Although network sockets can also be used for inter-process communication on the same host (via loopback address 127.0.0.1), UNIX Domain Sockets are more efficient for IPC:
There is no need to go through the network protocol stack, package and unpack, calculate checksums, maintain sequence numbers and responses, etc. It just copies the application layer data from one process to another.
This is because the IPC mechanism is essentially reliable communication, while network protocols are designed for unreliable communication.
UNIX Domain Socket also provides two API interfaces, stream-oriented and packet-oriented, similar to TCP and UDP, but message-oriented (UDP) UNIX Domain Socket is also reliable, and messages will neither be lost nor out of order.