net/SocketUtil: socket_bind_listen() returns UniqueSocketDescriptor

This commit is contained in:
Max Kellermann 2017-08-10 09:53:09 +02:00
parent 817e912025
commit da90f484aa
3 changed files with 18 additions and 30 deletions

View File

@ -24,6 +24,7 @@
#include "net/SocketAddress.hxx"
#include "net/SocketUtil.hxx"
#include "net/SocketError.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "net/Resolver.hxx"
#include "net/ToString.hxx"
#include "event/SocketMonitor.hxx"
@ -185,9 +186,9 @@ OneServerSocket::Open()
{
assert(!IsDefined());
int _fd = socket_bind_listen(address.GetFamily(),
SOCK_STREAM, 0,
address, 5);
auto _fd = socket_bind_listen(address.GetFamily(),
SOCK_STREAM, 0,
address, 5);
#ifdef HAVE_UN
/* allow everybody to connect */
@ -198,7 +199,7 @@ OneServerSocket::Open()
/* register in the EventLoop */
SetFD(_fd);
SetFD(_fd.Steal());
}
ServerSocket::ServerSocket(EventLoop &_loop)

View File

@ -21,44 +21,30 @@
#include "SocketUtil.hxx"
#include "SocketAddress.hxx"
#include "SocketError.hxx"
#include "system/fd_util.h"
#include "UniqueSocketDescriptor.hxx"
int
UniqueSocketDescriptor
socket_bind_listen(int domain, int type, int protocol,
SocketAddress address,
int backlog)
{
int fd, ret;
const int reuse = 1;
fd = socket_cloexec_nonblock(domain, type, protocol);
if (fd < 0)
UniqueSocketDescriptor fd;
if (!fd.CreateNonBlock(domain, type, protocol))
throw MakeSocketError("Failed to create socket");
ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
(const char *) &reuse, sizeof(reuse));
if (ret < 0) {
auto error = GetSocketError();
close_socket(fd);
throw MakeSocketError(error, "setsockopt() failed");
}
if (!fd.SetReuseAddress())
throw MakeSocketError("setsockopt() failed");
ret = bind(fd, address.GetAddress(), address.GetSize());
if (ret < 0) {
auto error = GetSocketError();
close_socket(fd);
throw MakeSocketError(error, "Failed to bind socket");
}
if (!fd.Bind(address))
throw MakeSocketError("Failed to bind socket");
ret = listen(fd, backlog);
if (ret < 0) {
auto error = GetSocketError();
close_socket(fd);
throw MakeSocketError(error, "Failed to listen on socket");
}
if (!fd.Listen(backlog))
throw MakeSocketError("Failed to listen on socket");
#if defined(HAVE_STRUCT_UCRED) && defined(SO_PASSCRED)
setsockopt(fd, SOL_SOCKET, SO_PASSCRED,
setsockopt(fd.Get(), SOL_SOCKET, SO_PASSCRED,
(const char *) &reuse, sizeof(reuse));
#endif

View File

@ -26,6 +26,7 @@
#ifndef MPD_SOCKET_UTIL_HXX
#define MPD_SOCKET_UTIL_HXX
class UniqueSocketDescriptor;
class SocketAddress;
/**
@ -43,7 +44,7 @@ class SocketAddress;
* ignore errors
* @return the socket file descriptor
*/
int
UniqueSocketDescriptor
socket_bind_listen(int domain, int type, int protocol,
SocketAddress address,
int backlog);