UDP client source port in C?

I am writing a UDP client, and I need to specify the source port of my UDP packet in my data to send.

  • How can my program get the random port number generated by kernal that the udp client uses to send data to the voip server. so
  • How can I specify a specific UDP source port before sending data.

I will be very grateful. Please reply to me as soon as possible. At the moment, my project is stopped.

+6
source share
2 answers

Use bind to bind your socket to port 0, which allows you to use getsockname to get the port. You can also bind your socket to a specific port if you want.

for example (assuming the IPv4 socket, 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); 

Alternatively, if you are communicating with the same server, you can use connect in your UDP socket (which also gives you a convenient side effect that allows you to use send instead of sendto and the UDP socket only accepts datagrams from your β€œconnected” peer), then use getsockname to get the local port / address. You can still bind your socket before 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); 
+7
source

You must bind(2) your socket to the port of your choice. See also man 7 ip and man 7 udp .

+2
source

Source: https://habr.com/ru/post/892581/


All Articles