odyssey/third_party/machinarium/sources/bind.c

53 lines
881 B
C
Raw Normal View History

2017-03-21 12:30:50 +00:00
/*
* machinarium.
*
* cooperative multitasking engine.
*/
#include <machinarium.h>
#include <machinarium_private.h>
2017-03-21 12:30:50 +00:00
MACHINE_API int
machine_bind(machine_io_t *obj, struct sockaddr *sa)
2017-03-21 12:30:50 +00:00
{
mm_io_t *io = mm_cast(mm_io_t*, obj);
2017-05-30 14:00:16 +00:00
mm_errno_set(0);
2017-04-11 14:39:20 +00:00
if (io->connected) {
2017-05-30 14:00:16 +00:00
mm_errno_set(EINPROGRESS);
2017-03-29 11:58:27 +00:00
return -1;
}
2017-04-11 14:39:20 +00:00
int rc;
rc = mm_io_socket(io, sa);
if (rc == -1)
goto error;
rc = mm_socket_set_reuseaddr(io->fd, 1);
if (rc == -1) {
2017-05-30 14:00:16 +00:00
mm_errno_set(errno);
2017-04-11 14:39:20 +00:00
goto error;
}
if (sa->sa_family == AF_INET6) {
rc = mm_socket_set_ipv6only(io->fd, 1);
if (rc == -1) {
mm_errno_set(errno);
goto error;
}
}
2017-04-11 14:39:20 +00:00
rc = mm_socket_bind(io->fd, sa);
if (rc == -1) {
2017-05-30 14:00:16 +00:00
mm_errno_set(errno);
2017-04-11 14:39:20 +00:00
goto error;
}
rc = machine_io_attach(obj);
if (rc == -1)
goto error;
2017-03-21 12:30:50 +00:00
return 0;
2017-04-11 14:39:20 +00:00
error:
if (io->fd != -1) {
close(io->fd);
io->fd = -1;
}
io->handle.fd = -1;
return -1;
2017-03-21 12:30:50 +00:00
}