I am writing a UDP client and I need to mention the source port of my UDP packet in my data to send.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With