简体   繁体   English

C 中的 UDP 客户端源端口?

[英]UDP Client Source port in C?

I am writing a UDP client and I need to mention the source port of my UDP packet in my data to send.我正在编写一个 UDP 客户端,我需要在要发送的数据中提及我的 UDP 数据包的源端口。

  1. How my program can get the random port number generated by kernal which udp client is using to send data to voip server.我的程序如何获取内核生成的随机端口号,udp 客户端正在使用该端口号将数据发送到 voip 服务器。 so所以
  2. How can i specify a specific UDP source port before sending data.如何在发送数据之前指定特定的 UDP 源端口。

I will be very very thankful.我将非常感谢。 Please reply me as soon as possible.请尽快回复我。 My project is stopped at this point.我的项目此时已停止。

Use bind to bind your socket to port 0, which will allow you to use getsockname to get the port.使用bind将您的套接字绑定到端口 0,这将允许您使用getsockname获取端口。 you can also bind your socket to a specific port, if you wish.如果您愿意,您还可以将您的套接字绑定到特定端口。

eg (assuming IPv4 socket, no error checking):例如(假设 IPv4 套接字,没有错误检查):

struct sockaddr_in sin = {};
socklen_t slen;
int sock;
short unsigned int port;

sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = 0;

bind(sock, (struct sockaddr *)&sin, sizeof(sin));
/* Now bound, get the address */
slen = sizeof(sin);
getsockname(sock, (struct sockaddr *)&sin, &slen);
port = ntohs(sin.sin_port);

Alternately, if you are communicating with a single server, you can use connect on your UDP socket (which also gives you the handy side effect of allowing you to use send instead of sendto , and making the UDP socket only accept datagrams from your "connected" peer), then use getsockname to obtain your local port/address.或者,如果您正在与单个服务器通信,则可以在 UDP 套接字上使用connect (这也为您提供了方便的副作用,即允许您使用send而不是sendto ,并使 UDP 套接字仅接受来自“已连接”的数据报" peer),然后使用getsockname获取您的本地端口/地址。 You may still choose to bind your socket prior to using connect .您仍然可以选择在使用connect之前绑定您的套接字。

eg:例如:

struct sockaddr_in sin = {};
socklen_t slen;
int sock;
short unsigned int port;

sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
/* set sin to your target host... */
...
connect(sock, (struct sockaddr *)&sin, sizeof(sin));
/* now retrieve the address as before */
slen = sizeof(sin);
getsockname(sock, (struct sockaddr *)&sin, &slen);
port = ntohs(sin.sin_port);

You should bind(2) your socket to a port of your choosing.您应该将您的套接字bind(2)到您选择的端口。 See also man 7 ip and man 7 udp .另请参见man 7 ipman 7 udp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM