获取UDP套接字随机端口 [英] Get random port for UDP socket

查看:1773
本文介绍了获取UDP套接字随机端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个程序,将通过UDP套接字在同一台计算机上的其他程序通信。它会从标准输入读取命令,而且其中的一些命令将使发送/收到的报文不停止执行。我读过一些信息在那里,但因为我不熟悉socket编程,需要得到这个快速完成,我有以下问题:

I need to create a program that will communicate with other programs on the same computer via UDP sockets. It will read commands from stdin, and some of this commands will make it to send/recieve packets without halting execution. I've read some information out there, but since I'm not familiar with socket programming and need to get this done quickly, I have the following questions:


  1. 我需要为程序来听一个随机的未使用的端口,并保留它,以便其他程序可以用这个沟通,也是端口没有被其他程序的保留。我还需要存储上为将来使用一个可变的端口号。

  2. 由于通信是整个过程在同一台机器上,我想知道如果我可以使用PF_LOCAL。

另外这种插座的设置的code样品将受到欢迎,以及发送/ recieving字符串的例子。

Also a code sample of the setup of such socket would be welcome, as well as an example of sending/recieving character strings.

推荐答案

呼叫绑定()指定端口0这将允许操作系统选择一个未使用的端口。然后,您可以使用 getsockname()中检索所选择的端口。

Call bind() specifying port 0. That will allow the OS to pick an unused port. You can then use getsockname() to retreive the chosen port.

这篇关于获取UDP套接字随机端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆