icinga2/base/tcpsocket.cpp

59 lines
1.1 KiB
C++
Raw Normal View History

2012-03-28 13:24:49 +02:00
#include "i2-base.h"
using namespace icinga;
void TCPSocket::MakeSocket(void)
{
assert(GetFD() == INVALID_SOCKET);
2012-03-28 13:24:49 +02:00
int fd = socket(AF_INET, SOCK_STREAM, 0);
2012-04-04 16:02:19 +02:00
if (fd == INVALID_SOCKET) {
2012-04-18 15:22:25 +02:00
SocketErrorEventArgs sea;
2012-04-04 16:02:19 +02:00
#ifdef _WIN32
2012-04-18 15:22:25 +02:00
sea.Code = WSAGetLastError();
2012-04-04 16:02:19 +02:00
#else /* _WIN32 */
2012-04-18 15:22:25 +02:00
sea.Code = errno;
2012-04-04 16:02:19 +02:00
#endif /* _WIN32 */
2012-04-18 15:22:25 +02:00
sea.Message = FormatErrorCode(sea.Code);
OnError(sea);
2012-04-04 16:02:19 +02:00
}
SetFD(fd);
2012-03-28 13:24:49 +02:00
}
void TCPSocket::Bind(unsigned short port)
{
Bind(NULL, port);
}
void TCPSocket::Bind(const char *hostname, unsigned short port)
{
2012-04-19 09:18:54 +02:00
#ifndef _WIN32
const int optTrue = 1;
setsockopt(GetFD(), SOL_SOCKET, SO_REUSEADDR, (char *)&optTrue, sizeof(optTrue));
#endif /* _WIN32 */
2012-03-28 13:24:49 +02:00
2012-04-19 09:18:54 +02:00
sockaddr_in sin;
2012-03-28 13:24:49 +02:00
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = hostname ? inet_addr(hostname) : htonl(INADDR_ANY);
sin.sin_port = htons(port);
int rc = ::bind(GetFD(), (sockaddr *)&sin, sizeof(sin));
2012-04-04 16:02:19 +02:00
if (rc < 0) {
2012-04-18 15:22:25 +02:00
SocketErrorEventArgs sea;
2012-04-04 16:02:19 +02:00
#ifdef _WIN32
2012-04-18 15:22:25 +02:00
sea.Code = WSAGetLastError();
2012-04-04 16:02:19 +02:00
#else /* _WIN32 */
2012-04-18 15:22:25 +02:00
sea.Code = errno;
2012-04-04 16:02:19 +02:00
#endif /* _WIN32 */
2012-04-18 15:22:25 +02:00
sea.Message = FormatErrorCode(sea.Code);
2012-04-04 16:02:19 +02:00
2012-04-18 15:22:25 +02:00
OnError(sea);
2012-04-04 16:02:19 +02:00
Close();
2012-04-04 16:02:19 +02:00
}
2012-03-28 13:24:49 +02:00
}