I know the question has been asked already, but i seem to be some kind of "special" since my code doesn't work. Instruction is "bind with port 0 and use getsockname to get port". What am i doing wrong...
struct sockaddr_in sa;
sa.sin_port=htons(0);
sa.sin_addr.s_addr=htonl(INADDR_ANY);
sa.sin_family=AF_INET;
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr *serverptr = (struct sockaddr*)&sa;
bind(sock, serverptr,sizeof(sa));
socklen_t s=sizeof(sa);
int g=getsockname(sock,serverptr,&s);
g always prints as 0.
EDIT: it was so much simpler, just sa.sin_port Dumb question.
Most of Berkley Socket API functions use very simple convention: result returned is the operation success indication. So, zero means OK, negative means error. To play safe, you have always to check it, and your code lacks this verification for the socket()
, bind()
, and getsockname()
calls:
...
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
// log the error, etc
return;
}
int res = bind(sock, serverptr, sizeof(sa));
if (res < 0) {
// log the error, etc
close(sock);
return;
}
socklen_t s = sizeof(sa);
res = getsockname(sock, serverptr, &s);
if (res < 0) {
// log the error, etc
close(sock);
return;
}
...