socket_getpeername

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_getpeername获取套接字远端名字,返回主机名和端口号或是 Unix 文件系统路径,具体取决于套接字类型

说明

socket_getpeername(Socket $socket, string &$address, int &$port = null): bool

获取套接字远端名字,返回主机名和端口号或是 Unix 文件系统路径,具体取决于套接字类型。

参数

socket

socket_create()socket_accept() 创建的 Socket 实例。

address

如果给定套接字的类型是 AF_INETAF_INET6socket_getpeername() 将在参数 address 上返回对端(远端) IP 地址 (例如:127.0.0.1fe80::1),如果存在端口号,也将关联到 port 参数。

如果给定套接字的类型是 AF_UNIXsocket_getpeername() 将在 address 参数中返回 Unix 文件系统路径(例如:/var/run/daemon.sock)。

port

如果提供此参数,它将保存 address 关联的端口号。

返回值

成功时返回 true, 或者在失败时返回 false。 如果套接字类型不是 AF_INETAF_INET6AF_UNIX 中的任意一个,socket_getpeername() 也可能返回 false,在此情况下,套接字最后的错误码不会更新。

更新日志

版本 说明
8.0.0 现在 socketSocket 实例, 之前是 resource

注释

注意:

socket_getpeername() 不应该用于 socket_accept() 创建的 AF_UNIX 类型套接字。只有使用 socket_connect() 创建的套接字或调用过 socket_bind() 的服务端套接字会返回有意义的值。

注意:

为了让 socket_getpeername() 返回有意义的值,套接字使用 “peer“ 的概念是有意义的(the socket it is applied upon must of course be one for which the concept of "peer" makes sense)。

参见

add a note add a note

User Contributed Notes 2 notes

up
5
redph0enix at hotmail dot com
20 years ago
socket_getpeername will not work for UDP sockets. Instead, use socket_recvfrom - it provides the IP address and port of the source server - eg:

$size=socket_recvfrom($socket,$input,65535,0,$ipaddress,$port);
echo "Received [$input] ($size bytes) from IP $ipaddress Port $port\n";
up
3
Anonymous
8 years ago
The reason it won't work for UDP is that UDP is stateless; logically there are no peers other than at the time a packet is sent or received. Or more strictly, a UDP socket can interact with 0..N peers.
To Top