How to let kernel choose a port number in the range (1024,5000) in TCP socket programming

Anonymous picture Anonymous · May 27, 2009 · Viewed 30.9k times · Source

When I run the following code:

struct   sockaddr_in sin;
int addrlen;   
addrlen=sizeof(sin);   
memset(&sin, 0, sizeof(sin));  
sin.sin_family = AF_INET;  
sin.sin_addr.s_addr=inet_addr("123.456.789.112");  
sin.sin_port=htons(0); // so that the kernel reserves a unique port for us  
sd_server = socket(PF_INET, SOCK_STREAM, 0);  
bind(sd_server, (struct sockaddr *) &sin, sizeof(sin));  
getsockname(sd_server,(struct sockaddr*)&sin,&addrlen);  
port=ntohs(sin.sin_port); 
printf("port number = %d\n",port);

According to sockets, I must get a port number between 1024 and 5000, but I'm getting port numbers around 30,000.
What should I do?

Answer

mark4o picture mark4o · May 29, 2009

Port numbers have a range of 0..65535 (although often 0 has special meaning). In the original BSD TCP implementation, only root can bind to ports 1..1023, and dynamically assigned ports were assigned from the range 1024..5000; the others were available for unprivileged static assignment. These days 1024..5000 is often not enough dynamic ports, and IANA has now officially designated the range 49152..65535 for dynamic port assignment. However even that is not enough dynamic ports for some busy servers, so the range is usually configurable (by an administrator). On modern Linux and Solaris systems (often used as servers), the default dynamic range now starts at 32768. Mac OS X and Windows Vista default to 49152..65535.

linux$ cat /proc/sys/net/ipv4/ip_local_port_range 
32768   61000

solaris$ /usr/sbin/ndd /dev/tcp tcp_smallest_anon_port tcp_largest_anon_port
32768

65535

macosx$ sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
net.inet.ip.portrange.first: 49152
net.inet.ip.portrange.last: 65535

vista> netsh int ipv4 show dynamicport tcp
Protocol tcp Dynamic Port Range
---------------------------------
Start Port : 49152
Number of Ports : 16384