Sockets, PHP, local port

感情迁移 提交于 2019-12-11 06:29:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!