SocketUtil.cxx 2.04 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 31 32 33
{
	int fd, ret;
	const int reuse = 1;

34
	fd = socket_cloexec_nonblock(domain, type, protocol);
35 36
	if (fd < 0)
		throw MakeSocketError("Failed to create socket");
37 38

	ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
39
			 (const char *) &reuse, sizeof(reuse));
40
	if (ret < 0) {
41
		auto error = GetSocketError();
42
		close_socket(fd);
43
		throw MakeSocketError(error, "setsockopt() failed");
44 45
	}

46
	ret = bind(fd, address.GetAddress(), address.GetSize());
47
	if (ret < 0) {
48
		auto error = GetSocketError();
49
		close_socket(fd);
50
		throw MakeSocketError(error, "Failed to bind socket");
51 52 53 54
	}

	ret = listen(fd, backlog);
	if (ret < 0) {
55
		auto error = GetSocketError();
56
		close_socket(fd);
57
		throw MakeSocketError(error, "Failed to listen on socket");
58 59
	}

60
#if defined(HAVE_STRUCT_UCRED) && defined(SO_PASSCRED)
61 62
	setsockopt(fd, SOL_SOCKET, SO_PASSCRED,
		   (const char *) &reuse, sizeof(reuse));
63 64 65 66
#endif

	return fd;
}
67 68 69 70 71 72 73

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

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