SocketUtil.cxx 2.02 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
21
#include "SocketUtil.hxx"
22
#include "SocketAddress.hxx"
23
#include "SocketError.hxx"
24
#include "system/fd_util.h"
25

26 27
int
socket_bind_listen(int domain, int type, int protocol,
28
		   SocketAddress address,
29
		   int backlog,
30
		   Error &error)
31 32 33 34
{
	int fd, ret;
	const int reuse = 1;

35
	fd = socket_cloexec_nonblock(domain, type, protocol);
36
	if (fd < 0) {
37 38
		SetSocketError(error);
		error.AddPrefix("Failed to create socket: ");
39 40 41 42
		return -1;
	}

	ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
43
			 (const char *) &reuse, sizeof(reuse));
44
	if (ret < 0) {
45 46
		SetSocketError(error);
		error.AddPrefix("setsockopt() failed: ");
47
		close_socket(fd);
48 49 50
		return -1;
	}

51
	ret = bind(fd, address.GetAddress(), address.GetSize());
52
	if (ret < 0) {
53
		SetSocketError(error);
54
		close_socket(fd);
55 56 57 58 59
		return -1;
	}

	ret = listen(fd, backlog);
	if (ret < 0) {
60 61
		SetSocketError(error);
		error.AddPrefix("listen() failed: ");
62
		close_socket(fd);
63 64 65
		return -1;
	}

66
#if defined(HAVE_STRUCT_UCRED) && defined(SO_PASSCRED)
67 68
	setsockopt(fd, SOL_SOCKET, SO_PASSCRED,
		   (const char *) &reuse, sizeof(reuse));
69 70 71 72
#endif

	return fd;
}
73 74 75 76 77 78 79

int
socket_keepalive(int fd)
{
	const int reuse = 1;

	return setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
80
			  (const char *)&reuse, sizeof(reuse));
81
}