Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 28 Feb 2002 16:43:28 -0600
From:      "Mike Meyer" <mwm-dated-1015368208.edb554@mired.org>
To:        "Richard Kaestner" <richard.kaestner@ycn.com>
Cc:        questions@freebsd.org
Subject:   RE: Q: Sockets - how to find a free and valid port number
Message-ID:  <15486.45712.363005.621922@guru.mired.org>
In-Reply-To: <61960424@toto.iv>

next in thread | previous in thread | raw e-mail | index | archive | help
Richard Kaestner <richard.kaestner@ycn.com> 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.

	<mike
--
Mike Meyer <mwm@mired.org>			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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?15486.45712.363005.621922>