Chris
Chris

Reputation: 40641

When sending a UDP packet, how do you get back the system-assigned outgoing port? (BSD C sockets)

When sending a UDP packet, how do you get back the system-assigned outgoing port? After sending the packet below, i need to immediately bind to and listen on whichever random port it chose for me, to get any responses to my broadcast.

// Open a socket
int sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

// Enable broadcast
int broadcastEnable=1;
setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));

// Configure the port and ip we want to send to
struct sockaddr_in broadcastAddr; // Make an endpoint
memset(&broadcastAddr, 0, sizeof(broadcastAddr));
broadcastAddr.sin_family = AF_INET;
inet_pton(AF_INET, "239.255.255.250", &broadcastAddr.sin_addr); // Set the broadcast IP address
broadcastAddr.sin_port = htons(1900); // Set port 1900

// Send it
char *request = "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:1\r\n\r\n";
sendto(sd, request, strlen(request), 0, (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));
close(sd);

Upvotes: 3

Views: 787

Answers (2)

caf
caf

Reputation: 239071

You don't need to find the port - just call recv() or recvfrom() on the socket that you used to send, and it will use the same local port (the port becomes bound when you do the sendto()).

You can also call getsockname() on the sending socket to find the port number for informational purposes, but you should still use the sending socket to receive - if you don't, there's a race condition between binding the socket and the response coming back from the network that might cause you to lose responses.

Upvotes: 6

sarnold
sarnold

Reputation: 104080

I believe you're looking for the getsockname(2) call:

   int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

DESCRIPTION
   getsockname() returns the current address to which the socket
   sockfd is bound, in the buffer pointed to by addr.  The addrlen
   argument should be initialized to indicate the amount of space
   (in bytes) pointed to by addr.  On return it contains the actual
   size of the socket address.

Upvotes: 1

Related Questions