如何在PHP中连接不同端口的套​​接字?

发布于 2024-11-12 05:22:27 字数 1139 浏览 0 评论 0原文

这段代码运行良好。 我在系统中的端口:80 中成功测试了套接字连接,但无法在不同的端口中连接。

<?php
echo "<pre>";
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = 8000;

/* Get the IP address for the target host. */
$address = gethostbyname('localhost');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}


echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";

?>

输出:

Attempting to connect to '127.0.0.1' on port '8000'...socket_connect() failed.
Reason: () Connection refused
Closing socket...OK.

我需要连接到 80 以外的端口,请问有什么想法吗? 谢谢

This code is working fine.
I am successfully tested socket connection in my system in port:80 but not able to connect in different port .

<?php
echo "<pre>";
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = 8000;

/* Get the IP address for the target host. */
$address = gethostbyname('localhost');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}


echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";

?>

Output:

Attempting to connect to '127.0.0.1' on port '8000'...socket_connect() failed.
Reason: () Connection refused
Closing socket...OK.

I need to connect in port different than 80, so please any Idea?
Thank You

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一场春暖 2024-11-19 05:22:27

如果没有打开服务器套接字,则无法连接到通用端口。

You can't connect to a generic port if there isn't a server socket opened there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文