2001-10-06 14:13:28 +00:00
|
|
|
#include "CTCPListenSocket.h"
|
|
|
|
#include "CTCPSocket.h"
|
|
|
|
#include "CNetworkAddress.h"
|
|
|
|
#include "CThread.h"
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/socket.h>
|
|
|
|
#include <netinet/in.h>
|
|
|
|
|
|
|
|
//
|
|
|
|
// CTCPListenSocket
|
|
|
|
//
|
|
|
|
|
|
|
|
CTCPListenSocket::CTCPListenSocket()
|
|
|
|
{
|
|
|
|
m_fd = socket(PF_INET, SOCK_STREAM, 0);
|
|
|
|
if (m_fd == -1) {
|
|
|
|
throw XSocketCreate();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
CTCPListenSocket::~CTCPListenSocket()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
close();
|
|
|
|
}
|
|
|
|
catch (...) {
|
|
|
|
// ignore
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void CTCPListenSocket::bind(
|
2001-10-14 16:58:01 +00:00
|
|
|
const CNetworkAddress& addr)
|
2001-10-06 14:13:28 +00:00
|
|
|
{
|
|
|
|
if (::bind(m_fd, addr.getAddress(), addr.getAddressLength()) == -1) {
|
|
|
|
if (errno == EADDRINUSE) {
|
|
|
|
throw XSocketAddressInUse();
|
|
|
|
}
|
|
|
|
throw XSocketBind();
|
|
|
|
}
|
|
|
|
if (listen(m_fd, 3) == -1) {
|
|
|
|
throw XSocketBind();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2001-10-14 16:58:01 +00:00
|
|
|
ISocket* CTCPListenSocket::accept()
|
2001-10-06 14:13:28 +00:00
|
|
|
{
|
|
|
|
for (;;) {
|
|
|
|
struct sockaddr addr;
|
|
|
|
socklen_t addrlen = sizeof(addr);
|
|
|
|
CThread::testCancel();
|
|
|
|
int fd = ::accept(m_fd, &addr, &addrlen);
|
|
|
|
if (fd == -1) {
|
|
|
|
CThread::testCancel();
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return new CTCPSocket(fd);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2001-10-14 16:58:01 +00:00
|
|
|
void CTCPListenSocket::close()
|
2001-10-06 14:13:28 +00:00
|
|
|
{
|
|
|
|
if (m_fd == -1) {
|
|
|
|
throw XIOClosed();
|
|
|
|
}
|
|
|
|
if (::close(m_fd) == -1) {
|
|
|
|
throw XIOClose();
|
|
|
|
}
|
|
|
|
m_fd = -1;
|
|
|
|
}
|