From owner-freebsd-questions Thu Feb 28 14:43:49 2002 Delivered-To: freebsd-questions@freebsd.org Received: from mired.org (dsl-64-192-6-133.telocity.com [64.192.6.133]) by hub.freebsd.org (Postfix) with SMTP id 592EB37B421 for ; Thu, 28 Feb 2002 14:43:31 -0800 (PST) Received: (qmail 20591 invoked by uid 100); 28 Feb 2002 22:43:28 -0000 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <15486.45712.363005.621922@guru.mired.org> Date: Thu, 28 Feb 2002 16:43:28 -0600 To: "Richard Kaestner" Cc: questions@freebsd.org Subject: RE: Q: Sockets - how to find a free and valid port number In-Reply-To: <61960424@toto.iv> X-Mailer: VM 6.90 under 21.1 (patch 14) "Cuyahoga Valley" XEmacs Lucid X-face: "5Mnwy%?j>IIV\)A=):rjWL~NB2aH[}Yq8Z=u~vJ`"(,&SiLvbbz2W`;h9L,Yg`+vb1>RG% *h+%X^n0EZd>TM8_IB;a8F?(Fb"lw'IgCoyM.[Lg#r\ From: "Mike Meyer" X-Delivery-Agent: TMDA/0.46 (Python 2.2; freebsd-4.5-STABLE-i386) Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.ORG Richard Kaestner types: > I am working on a socket client, which should: > - connect to a server, > - supply a "return" socket port (similar to ftp) > - continue communication on a second socket > > (Everything is on an Intranet. I was told, the firewall is > secure. And my client should run as ordinary user) > > Up to now, I could only find rresvport (2) (which returns a port > in the privileged area) Note that the concept of reserved port is really a Unixism that has crept into the internet at large. Most other systems don't control them the way Unix does. > However, I would prefer non-privileged. > Could anyone show me a way to get such a port number? You don't really get the port number. You do a bind or connect with a port number of 0, and the system chooses a port number for you. The default is a number between 1024 and 5000, which isn't something you want to use if this has to go through a firewall. You can use setsockopt to specify one of a number of different ranges for it to choose from like so: int sock, on; struct sockaddr_in sa; bzero(&sa, sizeo(sa)); sa.sin_len = sizeof(sa) ; sa.sin_family = PF_INET ; sock = socket(sa.sin_family, SOCK_STREAM, IPPROTO_IP) ; on = IP_PORTRANGE_HIGH ; // Or IP_PORTRANGE_DEFAULT setsockopt(sock, IPPROTO_IP, IP_PORTRANGE, (char *)&on) ; bind(sock, &sa, sizeof(sa)) ; and your port number is in sa.sin_port. The port ranges are defined/described in netinet/in.h. I've probably screwed something up, and of course you should verify that all those operations succeeded. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message