usr/src/cmd/rad/mod/rad_listen.c
author David Powell <david.e.powell@oracle.com>
Thu, 05 May 2011 13:16:34 -0700
changeset 698 3c730b38d1b0
parent 696 1ce0573e4536
permissions -rw-r--r--
18261 panel packages should depend on visual-panels-core 18262 listen_on_port doesn't fully initialize sockaddr structure

/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>

#include "rad_modapi.h"

int
listen_on_port(int port, boolean_t local)
{
	struct sockaddr_in6 sa = {
	    .sin6_family = AF_INET6,
	    .sin6_port = htons(port),
	    .sin6_addr = (local ? in6addr_loopback : in6addr_any)
	};
	int fd, option;

	rad_log(RL_DEBUG, "attempting to listen on port %d (%s)", port,
	    local ? "loopback only" : "all addresses");

	if ((fd = socket(AF_INET6, SOCK_STREAM, 0)) == -1) {
		rad_log(RL_ERROR, "failed to create socket: %s",
		    strerror(errno));
		return (-1);
	}

	option = 1;
	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option,
	    sizeof (option)) == -1) {
		rad_log(RL_ERROR, "failed to set socket options: %s",
		    strerror(errno));
		return (-1);
	}

	if (bind(fd, (struct sockaddr *)&sa, sizeof (sa)) == -1) {
		rad_log(RL_ERROR, "failed to bind to address: %s",
		    strerror(errno));
		return (-1);
	}

	if (listen(fd, 15) == -1) {
		rad_log(RL_ERROR, "failed to listen on socket: %s",
		    strerror(errno));
		return (-1);
	}

	rad_log(RL_DEBUG, "listening on port %d (%s)", port,
	    local ? "loopback only" : "all addresses");

	return (fd);
}