开发者

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.

  1. How my program can get the random port number generated by kernal which udp client is using to send data to voip server. so
  2. How can i specify a specific UDP source port before sending data.

开发者_C百科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. you can also bind your socket to a specific port, if you wish.

eg (assuming IPv4 socket, no error checking):

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. You may still choose to bind your socket prior to using 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. See also man 7 ip and man 7 udp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜