I have a UDP client program that uses Berkley sockets and Winsock (depending on the platform).
Basically it uses getaddrinfo(), then socket(), then sendto(). sendto() takes the address info returned by getaddrinfo(). My code looks like this:
struct addrinfo hint;
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_DGRAM;
struct addrinfo *address;
getaddrinfo("127.0.0.1", "9999", &hint, &address);
SOCKET s = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
sendto(s, "test", 4, 0, address->ai_addr, address->ai_addrlen);
My question is, when is the local/ephemeral port number set? Is it set with the call to sendto()? If I send more data to a different server, does sendto() reuse the same ephemeral port number? How can I get the ephemeral port number (in a protocol independent way)? I know that knowing this may not be useful, and NAT can change it anyway, but I'm just trying to understand how it all works better.
I also know I can use bind() to set the local port, but my question is about what happens when the OS chooses the local port for me.
You want the
getsocknamefunction:It populates the given
sockaddrwith the address and port that the socket is bound to.This function is available in both winsock and Berkely sockets.