Reputation: 3865
I’ve heard the operating system chooses a random free port for the client.
And I've tried to catch the port number the operating system chooses.
Then I made a following tow sample programs.
sample.c shows
sin_port is 49210
sin_port is 49210
sin_port(getMyPortNum) is 0
sample2.c shows
sin_port is 0
sin_port is 0
sin_port(getMyPortNum) is 34936
Which is correct client port number that the operating system chooses?
I think last number of sample2.c is correct because 49210 of sample.c is not random always same number.
And why both programs behave differently?
OR how do these code in sample.c work for which aren’t needed in source?
struct sockaddr_in addr2;
socklen_t addr2_sz = sizeof(addr2);
int i;
int j;
Sample.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
main()
{
int sock;
struct sockaddr_in addr;
int sockaddr_in_size = sizeof(struct sockaddr_in);
struct sockaddr_in addr2;
socklen_t addr2_sz = sizeof(addr2);
int i;
int j;
printf("sin_port is %d\n",ntohs(addr.sin_port));
sock = socket(AF_INET, SOCK_DGRAM, 0);
bind(sock,(struct sockaddr *)&addr,sizeof(addr));
printf("sin_port is %d\n",ntohs(addr.sin_port));
printf("sin_port(getMyPortNum) is %d\n",ntohs(getMyPortNum(sock)));
}
int getMyPortNum(int sock)
{
struct sockaddr_in s;
socklen_t sz = sizeof(s);
getsockname(sock, (struct sockaddr *)&s, &sz);
return s.sin_port;
}
Sample2.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
main()
{
int sock;
struct sockaddr_in addr;
int sockaddr_in_size = sizeof(struct sockaddr_in);
// struct sockaddr_in addr2;
// socklen_t addr2_sz = sizeof(addr2);
// int i;
// int j;
printf("sin_port is %d\n",ntohs(addr.sin_port));
sock = socket(AF_INET, SOCK_DGRAM, 0);
bind(sock,(struct sockaddr *)&addr,sizeof(addr));
printf("sin_port is %d\n",ntohs(addr.sin_port));
printf("sin_port(getMyPortNum) is %d\n",ntohs(getMyPortNum(sock)));
}
int getMyPortNum(int sock)
{
struct sockaddr_in s;
socklen_t sz = sizeof(s);
getsockname(sock, (struct sockaddr *)&s, &sz);
return s.sin_port;
}
Upvotes: 0
Views: 1407
Reputation: 12586
You should bind()
the created sockets, giving the bind the pointer of the already initialized sockaddr_in structs as argument.
Upvotes: 1
Reputation: 182743
Neither program makes any sense. Neither does anything relating to a port but both try to print out a port.
Upvotes: 2