如何判断我是否将 UDP 数据包发送到开放端口?

发布于 2024-10-10 18:42:27 字数 365 浏览 6 评论 0原文

我正在编写一个 C 程序,需要检查目标计算机上打开的 UDP 端口。由于 UDP 是无连接的,因此我无法像 TCP 那样检查 connect() 的返回值。

send()sendto() 返回值也没有帮助。手册页指出:

   No  indication  of failure to deliver is implicit in a send().  Locally
   detected errors are indicated by a return value of -1.

如何判断我是否将 UDP 数据包发送到目标主机上的开放端口?

I am making a C program in which I need to check for opened UDP ports on the destination computer. Because UDP is connectionless, I can't check the return value of connect() like I can with TCP.

send() and sendto() return values are also no help. The manual page states:

   No  indication  of failure to deliver is implicit in a send().  Locally
   detected errors are indicated by a return value of -1.

How can I tell if I sent a UDP packet to an open port on the destination host?

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

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

发布评论

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

评论(2

小…红帽 2024-10-17 18:42:27

一般来说你做不到。

原则上,具有关闭端口的主机应发送回 ICMP 端口不可达。但他们常常不这样做;同样,宕机或无法访问的主机也不会发送此类消息。此外,某些防火墙会阻止该消息。

检索错误也是有问题的。 Linux 对于检索套接字上的错误具有定义明确但令人困惑的语义(有关一些信息,请参阅各种手册页、socket(7)、ip(7) 和 udp(7))。例如,当您执行不相关的 sendto() 时,您有时会看到先前报告的错误。其他操作系统的检索特定套接字错误的机制略有不同。

如果保证是另一个端口上的特定协议,您可以发送一个应引起特定响应的数据包(如果是您自己的协议,您可以添加“are you there”消息类型),然后您可以使用那。但一般来说,是否生成响应取决于应用程序,并且您无法区分没有任何监听的端口和有监听但决定不响应您的端口。

In general you can't do it.

In principle, a host with a closed port should send back an ICMP port-unreachable. But they often don't; likewise, a down or inaccessible host will not send such a message. Also, some firewalls will block the message.

Retrieving the error is also problematic. Linux has well-defined, but confusing semantics for retrieving errors on sockets (see the various man pages, socket(7), ip(7) and udp(7) for some info). You will sometimes see a previous error reported when you do an unrelated sendto() for example. Other OSs have slightly differing mechanisms for retrieving specific socket errors.

If it is guaranteed to be a particular protocol on the other port, you can send a packet which should elicit a particular response (if it is your own protocol, you can add an "are you there" message type), then you can use that. But in general, whether a response is generated is up to the application, and you cannot distinguish between a port with nothing listening, and a port with something listening which decides not to respond to you.

原谅我要高飞 2024-10-17 18:42:27

由于 UDP 是无连接的,因此您必须在应用程序代码中检查端口状态。例如,向端口发送数据包,并等待响应。如果您在某些应用程序特定时间内没有收到响应,则该端口不可用。

当然,您必须将其设计到发送端和接收端。

Since UDP is connectionless, you have to check the port status in your application code. For example, send a packet to the port, and wait for a response. If you don't get a response in some application specific time, the port isn't available.

You have to design this into both the sending and receiving end, of course.

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