Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP Client Source port in C?

Tags:

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.

I will be very very thankful. Please reply me as soon as possible. My project is stopped at this point.

like image 622
shan Avatar asked Jul 12 '11 14:07

shan


1 Answers

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);
like image 57
Hasturkun Avatar answered Sep 17 '22 13:09

Hasturkun