问题
I'm writing a PHP-based client using sockets for an existing system.
Implementing the protocol is basically working, but for the next step I need to know the local port, on which the socket is created.
On the server I have the following output: Socket[addr=/Client-IP,port=40546,localport=1338]
For communication to work, I need to get the port 40546 (or whatever it is when connecting). Sadly it is NOT possible to change the protocol for various reasons.
Thanks in advcance
Adrian
EDIT (Code snippet):
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, 192.168.0.12, 1338);
// Need to know local socket port (e.g. 40546)
$socketport = ??????
$message = "somestring";
$message = $protocol->encode($message, $socketport);
socket_write($socket, $message, strlen($message));
This is basically what it is. I need to know the port on the clientside, AFTER creating and connecting the socket, meaning there's no need to set it manually.
回答1:
I found out a function in php.net.I think this works for you.
socket_getsockname($socket, $ip, $port);
echo "ip: ".$ip;
echo "port: ".$port;
Here $ip
gives you the local addr and $port
gives you a local port no.
来源:https://stackoverflow.com/questions/21640660/sockets-php-local-port