#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "butil/fd_guard.h"
#include "butil/logging.h"
namespace butil {
int unix_socket_listen(const char* sockname, bool remove_previous_file) {
struct sockaddr_un addr;
addr.sun_family = AF_LOCAL;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", sockname);
fd_guard fd(socket(AF_LOCAL, SOCK_STREAM, 0));
if (fd < 0) {
PLOG(ERROR) << "Fail to create unix socket";
return -1;
}
if (remove_previous_file) {
remove(sockname);
}
if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
PLOG(ERROR) << "Fail to bind sockfd=" << fd << " as unix socket="
<< sockname;
return -1;
}
if (listen(fd, SOMAXCONN) != 0) {
PLOG(ERROR) << "Fail to listen to sockfd=" << fd;
return -1;
}
return fd.release();
}
int unix_socket_listen(const char* sockname) {
return unix_socket_listen(sockname, true);
}
int unix_socket_connect(const char* sockname) {
struct sockaddr_un addr;
addr.sun_family = AF_LOCAL;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", sockname);
fd_guard fd(socket(AF_LOCAL, SOCK_STREAM, 0));
if (fd < 0) {
PLOG(ERROR) << "Fail to create unix socket";
return -1;
}
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
PLOG(ERROR) << "Fail to connect to unix socket=" << sockname
<< " via sockfd=" << fd;
return -1;
}
return fd.release();
}
}