SocketUtil.cxx 2.13 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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 "SocketError.hxx"
23
#include "fd_util.h"
24

25 26
#include <unistd.h>

27
#ifndef WIN32
28
#include <sys/socket.h>
29
#else
30
#include <ws2tcpip.h>
31
#include <winsock.h>
32
#endif
33 34 35 36 37

#ifdef HAVE_IPV6
#include <string.h>
#endif

38 39 40 41
int
socket_bind_listen(int domain, int type, int protocol,
		   const struct sockaddr *address, size_t address_length,
		   int backlog,
42
		   Error &error)
43 44 45 46
{
	int fd, ret;
	const int reuse = 1;

47
	fd = socket_cloexec_nonblock(domain, type, protocol);
48
	if (fd < 0) {
49 50
		SetSocketError(error);
		error.AddPrefix("Failed to create socket: ");
51 52 53 54
		return -1;
	}

	ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
55
			 (const char *) &reuse, sizeof(reuse));
56
	if (ret < 0) {
57 58
		SetSocketError(error);
		error.AddPrefix("setsockopt() failed: ");
59
		close_socket(fd);
60 61 62 63 64
		return -1;
	}

	ret = bind(fd, address, address_length);
	if (ret < 0) {
65
		SetSocketError(error);
66
		close_socket(fd);
67 68 69 70 71
		return -1;
	}

	ret = listen(fd, backlog);
	if (ret < 0) {
72 73
		SetSocketError(error);
		error.AddPrefix("listen() failed: ");
74
		close_socket(fd);
75 76 77 78
		return -1;
	}

#ifdef HAVE_STRUCT_UCRED
79 80
	setsockopt(fd, SOL_SOCKET, SO_PASSCRED,
		   (const char *) &reuse, sizeof(reuse));
81 82 83 84
#endif

	return fd;
}
85 86 87 88 89 90 91

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

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