Home >Backend Development >PHP Tutorial >The difference between mysql_connect localhost and 127.0.0.1 (network layer explanation)_PHP tutorial
This article mainly introduces the difference between mysql_connect localhost and 127.0.0.1 (network layer explanation). This article starts from The network communication level explains their differences, friends in need can refer to it
connects.php
The code is as follows:
Use strace to get system calls:
The code is as follows:
#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.