Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 212
Anonymous Avatar asked May 27 '09 00:05

Anonymous


People also ask

What are the registered ports and range 1024 to 49151?

TCP/IP Ports Ports 0 through 1023 are defined as well-known ports. Registered ports are from 1024 to 49151. The remainder of the ports from 49152 to 65535 can be used dynamically by applications.

What port number is 1024?

Port numbers 0 - 1023 are used for well-known ports. Port numbers 1024 - 65535 are available for the following user applications: Port numbers 1024 - 49151 are reserved for user server applications. Port numbers 49152 - 65535 are reserved for clients.

What is the range of port number in TCP?

Port numbers range from 0 to 65536, but only ports numbers 0 to 1024 are reserved for privileged services and designated as well-known ports. This list of well-known port numbers specifies the port used by the server process as its contact port.


1 Answers

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 
like image 93
mark4o Avatar answered Sep 24 '22 08:09

mark4o