bool MessagePumpLibevent::Init() {
    int fds[2];
    if (pipe(fds)) {
        std::cerr << "pipe() failed, errno: " << errno;
        return false;
    }
    if (SetNonBlocking(fds[0])) {
        std::cerr << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
        return false;
    }
    if (SetNonBlocking(fds[1])) {
        std::cerr << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
        return false;
    }
    wakeup_pipe_out_ = fds[0];
    wakeup_pipe_in_ = fds[1];
    
    wakeup_event_ = new event;
    event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
              OnWakeup, this);
    event_base_set(event_base_, wakeup_event_);
    
    if (event_add(wakeup_event_, 0))
        return false;
    return true;
}
Example #2
0
	int ListenOn(Address &addr) {

	    ENTER_LOG;
	    fd_ = socket(AF_INET, SOCK_STREAM, 0);
	    if (fd_ < 0) {
		FATAL_LOG("create socket error: %d %s", errno, strerror(errno));
		LEAVE_ERR_LOG;
		return -1;
	    }
	    SetNonBlocking(fd_);
	    if (bind(fd_, (struct sockaddr*)&addr.GetSockaddr(), sizeof(struct sockaddr_in)) < 0) {
		FATAL_LOG("bind error: %d %s", errno, strerror(errno));
		close(fd_);
		LEAVE_ERR_LOG;
		return -3;
	    }
	    if (listen(fd_, 1024) < 0) {
		FATAL_LOG("listen error: %d %s", errno, strerror(errno));
		close(fd_);
		LEAVE_ERR_LOG;
		return -4;
	    }
	    LEAVE_LOG;
	    return 0;
	};
Example #3
0
 void SyncSend(const void* data, size_t size, Flags flags) final {
     SetNonBlocking(false);
     int f = 0;
     if (flags & MsgMore) f |= MSG_MORE;
     if (socket_.send(data, size, f) != static_cast<ssize_t>(size))
         throw Exception("Error during SyncSend", errno);
 }
Example #4
0
void async_connect(void *socket) {
	SOCKET sock = (SOCKET)socket;
	printf("do connect: %d\n", sock);
	struct sockaddr_in stSockAddr;
	memset(&stSockAddr, 0, sizeof(stSockAddr));

	stSockAddr.sin_family = AF_INET;
	stSockAddr.sin_port = htons(3980);
	int res = inet_pton(AF_INET, "91.228.153.235", &stSockAddr.sin_addr);

	if (0 > res) {
		throw "Unable to connect";
	} else if (0 == res) {
		throw "Unable to connect";
	}

	if (connect(sock, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr)) != 0) {
		throw "Unable to connect";
	}

	/* Connection succeeded */
	if (!SetNonBlocking(sock)) {
		DEBUG(net, 0, "setting non-blocking mode failed");
	}
}
UrRealtimeCommunication::UrRealtimeCommunication(
		std::condition_variable& msg_cond, const std::string& host,
		const unsigned int port /*=30003*/,
		unsigned int safety_count_max/*=12*/) {
    robot_state_ = new RobotStateRT(msg_cond);
	memset((char *) &serv_addr_, 0, sizeof(serv_addr_));
	sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd_ < 0) {
		print_fatal("ERROR opening socket");
	}
	server_ = gethostbyname(host.c_str());
	if (server_ == NULL) {
		print_fatal("ERROR, no such host");
	}
	serv_addr_.sin_family = AF_INET;
	memcpy((char *)&serv_addr_.sin_addr.s_addr, (char *)server_->h_addr, server_->h_length);
	serv_addr_.sin_port = htons(port);
	flag_ = 1;
	setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int));
	setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag_, sizeof(int));
	setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, (char *) &flag_, sizeof(int));
	SetNonBlocking(sockfd_, true);
	connected_ = false;
	keepalive_ = false;
	safety_count_ = safety_count_max + 1;
	safety_count_max_ = safety_count_max;
}
Example #6
0
bool CG_NetSocket::Initialize(int protocol)
{
	if (m_nCount++==0)
		if (!_NetStartUp(1,1)) return false;

	if (protocol==NETWORK_PROTOCOL_UDP)
	{
		m_socket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	}
	else 
	{
		m_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	}

	if(m_socket==INVALID_SOCKET) 
	{
		return false;
	}
	SetNonBlocking();
	
	//SetSendBufferSize(32*1024);
	//SetRecvBufferSize(16*1024);
	/*
	// test code 
	long arg = 1;
	int ret = setsockopt(m_socket,IPPROTO_TCP,TCP_NODELAYk,(char *)&arg,sizeof(arg));
	if(ret)
	{
		Sys_Log("socket: set tcp_nodelay failed");
	}
	*/
	return true;
}
Example #7
0
/**
 * Receive a packet at UDP level
 */
void NetworkUDPSocketHandler::ReceivePackets()
{
	for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
		struct sockaddr_storage client_addr;
		memset(&client_addr, 0, sizeof(client_addr));

		Packet p(this);
		socklen_t client_len = sizeof(client_addr);

		/* Try to receive anything */
		SetNonBlocking(s->second); // Some OSes seem to lose the non-blocking status of the socket
		int nbytes = recvfrom(s->second, (char*)p.buffer, SEND_MTU, 0, (struct sockaddr *)&client_addr, &client_len);

		/* We got some bytes for the base header of the packet. */
		if (nbytes > 2) {
			NetworkAddress address(client_addr, client_len);
			p.PrepareToRead();

			/* If the size does not match the packet must be corrupted.
			 * Otherwise it will be marked as corrupted later on. */
			if (nbytes != p.size) {
				DEBUG(net, 1, "received a packet with mismatching size from %s", address.GetAddressAsString());
				return;
			}

			/* Handle the packet */
			this->HandleUDPPacket(&p, &address);
		}
	}
}
Example #8
0
/**
 * Receive a packet at UDP level
 */
void NetworkUDPSocketHandler::ReceivePackets()
{
	for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
		for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP
			struct sockaddr_storage client_addr;
			memset(&client_addr, 0, sizeof(client_addr));

			Packet p(this);
			socklen_t client_len = sizeof(client_addr);

			/* Try to receive anything */
			SetNonBlocking(s->second); // Some OSes seem to lose the non-blocking status of the socket
			int nbytes = recvfrom(s->second, (char*)p.buffer, SEND_MTU, 0, (struct sockaddr *)&client_addr, &client_len);

			/* Did we get the bytes for the base header of the packet? */
			if (nbytes <= 0) break;    // No data, i.e. no packet
			if (nbytes <= 2) continue; // Invalid data; try next packet

			NetworkAddress address(client_addr, client_len);
			p.PrepareToRead();

			/* If the size does not match the packet must be corrupted.
			 * Otherwise it will be marked as corrupted later on. */
			if (nbytes != p.size) {
				DEBUG(net, 1, "received a packet with mismatching size from %s", address.GetAddressAsString());
				continue;
			}

			/* Handle the packet */
			this->HandleUDPPacket(&p, &address);
		}
	}
}
QHandler::QHandler(unsigned short qid) : qid(qid)
{
	// Default these to 0, so we won't handle anything.
	lowerHashLimit = 0;
	upperHashLimit = 0;

	std::cout << "Opening library..." << std::endl;
	h = nfq_open();
	if (h == 0) { throw std::runtime_error("Cannot open lib"); }
	// Unbind existing handler
	if (nfq_unbind_pf(h, AF_INET) < 0) {
	    std::cerr << "error during nfq_unbind_pf() - maybe this is ok\n";
	}
	// Bind new handler
	if (nfq_bind_pf(h, AF_INET) < 0) {
	    throw std::runtime_error("nfq_bind_pf failed");
	}
	qh = nfq_create_queue(h,  QueueId, &packet_callback, this);
	if (qh == 0) { throw std::runtime_error("Cannot create queue"); }
	// Set packet copy mode...
	if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
	    throw std::runtime_error("nfq_set_mode failed");
	}

	// Get the nl handle and file descriptor...
	nh = nfq_nfnlh(h);
	sock = nfnl_fd(nh);
	// So far so good.
	// Set our socket non blocking.
	SetNonBlocking(sock);
}
Example #10
0
    virtual int Create( int type,
                        int port )
    {
        char myname[MAXHOSTNAME+1];
        int err;
        struct sockaddr_in sa;
        struct hostent *hp;

        memset( &sa, 0, sizeof( struct sockaddr_in ) ); /* clear our address */
        gethostname( myname, MAXHOSTNAME );         /* who are we? */
        hp= gethostbyname( myname );                /* get our address info */

        if ( hp == NULL )                           /* we don't exist !? */
            return -1;

        sa.sin_family= hp->h_addrtype;              /* this is our host address */
        sa.sin_port= (u_short)htons( (u_short)port );                /* this is our port number */

        if (( m_Socket = socket( AF_INET, type, 0 ) ) < 0 ) /* create socket */
            return -1;

        if ( bind( m_Socket,  (struct sockaddr*) &sa, sizeof( struct sockaddr_in ) ) < 0 )
        {
            Close();
            return -1;
        }

        if (( err = SetNonBlocking() ) != 0 )
            return err;
    }
/**
 * Helper function to resolve a connected socket.
 * @param runp information about the socket to try not
 * @return the opened socket or INVALID_SOCKET
 */
static SOCKET ConnectLoopProc(addrinfo *runp)
{
	const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
	const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
	const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();

	SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
	if (sock == INVALID_SOCKET) {
		DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, strerror(errno));
		return INVALID_SOCKET;
	}

	if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);

	if (connect(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
		DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, strerror(errno));
		closesocket(sock);
		return INVALID_SOCKET;
	}

	/* Connection succeeded */
	if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);

	DEBUG(net, 1, "[%s] connected to %s", type, address);

	return sock;
}
Example #12
0
        void Socket::CreateUDPSocketToSendAndReceive()
        {
            // Create Socket
            CreateUDPSocket();

            // Set to not block
            SetNonBlocking();
        }
Example #13
0
//--------------------------------------------------------------------------------
bool ofxTCPManager::Connect(const char *pAddrStr, unsigned short usPort)
{
  sockaddr_in addr_in= {0};
  struct hostent *he;

  if (m_hSocket == INVALID_SOCKET){
	  return(false);
  }

  if ((he = gethostbyname(pAddrStr)) == NULL)
    return(false);

	addr_in.sin_family= AF_INET; // host byte order
	addr_in.sin_port  = htons(usPort); // short, network byte order
	addr_in.sin_addr  = *((struct in_addr *)he->h_addr);

	// set to non-blocking before connect
    bool wasBlocking = nonBlocking;
	if(m_dwTimeoutConnect != NO_TIMEOUT){
		SetNonBlocking(true);
	}

    int ret = connect(m_hSocket, (sockaddr *)&addr_in, sizeof(sockaddr));
    int err = 0;
    if(ret<0) err = ofxNetworkCheckError();
    // set a timeout
    if (ret < 0 && (err == OFXNETWORK_ERROR(INPROGRESS) || err == OFXNETWORK_ERROR(WOULDBLOCK)) && m_dwTimeoutConnect != NO_TIMEOUT) {
		ret = WaitSend(m_dwTimeoutConnect, 0);
		if(ret == 0) {
			socklen_t len = sizeof err;
			if (getsockopt(m_hSocket, SOL_SOCKET, SO_ERROR, (char*)&err, &len)<0){
				ret = SOCKET_ERROR;
			}else if(err != 0) {
				ret = SOCKET_ERROR;
            } 
		}
    }

	if(m_dwTimeoutConnect != NO_TIMEOUT){
		SetNonBlocking(wasBlocking);
	}
    
	return ret>=0;
}
Example #14
0
int CTcpSocket::Connect(sockaddr_in &toAddr)
{
        m_iSocket = socket(toAddr.sin_family,  SOCK_STREAM, 0);
        memcpy(&m_toAddr, &toAddr, sizeof(sockaddr_in));
        m_toLen = sizeof(sockaddr_in);
        int ret = connect(m_iSocket, (sockaddr*)&m_toAddr, m_toLen);
        if (ret == 0)
        SetNonBlocking();
        return ret;
}
Example #15
0
File: http.c Project: XHXaiXXR/code
void Addfd(int epollfd, int fd)
{
	struct epoll_event ev;
	ev.events = EPOLLIN | EPOLLET;
	ev.data.fd = fd;
	epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
	
	//由于epoll是高效的ET工作模式,所以必须设置fd为非阻塞的。
	SetNonBlocking(fd);
}
Example #16
0
bool CTcp::Accept(int iServerSocket)
{
    socklen_t len=sizeof(m_sAddress);
    if((m_iSock=accept(iServerSocket,(struct sockaddr*)&m_sAddress,&len))==-1){
        printf("accept socket error:%s(errno:%d)\n",strerror(errno),errno);
        return false;
    }
    SetNonBlocking();
    return true;
}
Example #17
0
        void Socket::CreateAndBindUDPSocket(const AdressImplementation& p_myAdress)
        {
            // Create socket
            CreateUDPSocket();

            // Bind socket to Receive incomming
            BindSocket(p_myAdress);

            // Set socket to non blocking
            SetNonBlocking();
        }
Example #18
0
//--------------------------------------------------------------------------------
bool ofxTCPManager::CheckIsConnected(){
#ifdef TARGET_WIN32
	fd_set fd;
	FD_ZERO(&fd);
	FD_SET(m_hSocket, &fd);
	timeval tv = { (time_t)0, 1 };
	if (select(0, &fd, NULL, NULL, &tv) == 1) {
		int so_error;
		socklen_t len = sizeof so_error;
		getsockopt(m_hSocket, SOL_SOCKET, SO_ERROR, (char*)&so_error, &len);
		if (so_error == 0) {
			u_long toread;
#ifdef TARGET_WIN32
			ioctlsocket(m_hSocket, FIONREAD, &toread);
#else
			ioctl(m_hSocket, FIONREAD, &toread);
#endif
			if (toread == 0) {
				return false;
			}
		}
    }
    return true;
#else
    bool wasBlocking = nonBlocking;
    SetNonBlocking(false);
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 1;
    if(setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout))<0){
        return true;
    }
    char buffer;
    int ret = recv(m_hSocket, &buffer, 1, MSG_PEEK);
    SetNonBlocking(wasBlocking);
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;
    setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
    return ret!=0;
#endif
}
Example #19
0
int CTcpSocket::Connect(const string & sAddr, short nPort)
{        
        m_iSocket = socket(AF_INET,  SOCK_STREAM, 0);
        m_toAddr.sin_family = AF_INET;
        m_toAddr.sin_port = htons(nPort);
        inet_aton(sAddr.c_str(), &(m_toAddr.sin_addr));
        m_toLen = sizeof(sockaddr_in);
        int ret = connect(m_iSocket, (sockaddr*)&m_toAddr, m_toLen);
        if (ret == 0)
        SetNonBlocking();
        return ret;
}
Example #20
0
File: worker.c Project: jxva/miaoox
static void InitWorkerSignals() {
    struct sigaction act, oact;
    int ret = socketpair(PF_UNIX, SOCK_STREAM, 0, signal_pipefd);
    SetNonBlocking(signal_pipefd[1]);
    assert(ret != -1);

    evCreateIOEvent(worker->poll, signal_pipefd[0], EV_READABLE, WorkerSignalHandler, NULL);

    SignalRegister(SIGCHLD, DispatchSignal, 1);
    SignalRegister(SIGTERM, DispatchSignal, 1);
    SignalRegister(SIGINT, DispatchSignal, 1);
    SignalRegister(SIGPIPE, SIG_IGN, 1)
}
Example #21
0
int CTcpSocket::Connect(const string &sAddr, short nPort, int nTimeOut)
{
	if( nTimeOut < 0 ) return -1;
	m_iSocket = socket(AF_INET,  SOCK_STREAM, 0);
	m_toAddr.sin_family = AF_INET;
	m_toAddr.sin_port = htons(nPort);
	inet_aton(sAddr.c_str(), &(m_toAddr.sin_addr));
	m_toLen = sizeof(sockaddr_in);

	SetNonBlocking();
	connect(m_iSocket, (sockaddr*)&m_toAddr, m_toLen);

	struct timeval tvSelectWait;
	tvSelectWait.tv_sec = nTimeOut;
	tvSelectWait.tv_usec = 0;

	fd_set setWrite;
	while(1)
	{
		FD_ZERO(&setWrite);
		FD_SET(m_iSocket, &setWrite);
		int nRet = 0;
		if((nRet = select(m_iSocket + 1, NULL, &setWrite , NULL, &tvSelectWait)) < 0)		// socket出错时返回-1,无事件时返回0 
		{
			if(errno == EINTR) continue;
			return -1;
		}
		else 
		{
			if(nRet == 0) 
			{
				return 1;				//超时 
			}
			else
			{
				int nError;
				socklen_t nSockLen = sizeof(nError);
				getsockopt(m_iSocket, SOL_SOCKET, SO_ERROR, &nError, &nSockLen);
				if (nError == 0)
				{
					return 0;						//连接成功 
				}
				else
				{
					return -1;						//连接失败
				}
			}
		}
	}	
}
Example #22
0
        void Socket::CreateWaitingTCPSocket(const AdressImplementation& p_myAdress, const uint8_t& p_maxConnections)
        {
            // Create Socket
            CreateTCPSocket();

            // Set adress and bind socket to port
            BindSocket(p_myAdress);

            // Set socket to nonblocking
            SetNonBlocking();

            // Set socket to listening with max number of connections to port
            listen(m_socketHandle, p_maxConnections);
        }
Example #23
0
HRESULT CTestPolling::CreateAndAddPipe()
{
    HRESULT hr = S_OK;
    PipePair pp = {};
    int ret = -1;
    int fds[2];
    ret = ::pipe(fds);
    
    ChkIfA(ret == -1, ERRNOHR);

    pp.readpipe = fds[0];
    pp.writepipe = fds[1];
    pp.fDataPending = false;

    ChkA(SetNonBlocking(pp.readpipe));
    ChkA(SetNonBlocking(pp.writepipe));

    _pipes.push_back(pp);

    ChkA(_spPolling->Add(fds[0], IPOLLING_READ)); 
    
Cleanup:
    return hr;
}
Example #24
0
/*server apply socket and bind*/
int ServerPrepare(char * ServerId)
{
    char ip[50] ="\0";
    socklen_t len;
    struct sockaddr_in raddr;
    struct epoll_event event;
    getlocalhostip();
    printf("ip is %s\n",ipptr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr =  inet_addr(ipptr);      //set ip
    server_addr.sin_port = htons(0);                 //set port
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        fprintf(stderr, "socket error:%s\n\a", strerror(errno));
        exit(1);
    }
    epollfd = epoll_create(MAX_CONNECT);
    SetNonBlocking(sockfd);
    event.data.fd = sockfd;
    event.events = EPOLLIN | EPOLLRDHUP;
    epoll_ctl(epollfd,EPOLL_CTL_ADD,sockfd,&event);
    if(bind(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
    {
        fprintf(stderr, "bind error:%s\n\a", strerror(errno));
        close(sockfd); 
        exit(1);
    } 
    len=sizeof(raddr);
    if(getsockname(sockfd,(struct sockaddr *)&raddr,&len)<0)
    {
	printf("getsockname failed!\n");
	return -1;
    }
    strcpy(ip,inet_ntoa(raddr.sin_addr));
    //printf("ip is %s,port is %d\n",ip,ntohs(raddr.sin_port));
    sprintf(ports,"%d",ntohs(raddr.sin_port));
    //printf("ports is %s\n",ports);
    ServerInfo(ServerId,ip,ports);
    if(listen(sockfd,MAX_CONNECT_QUEUE) == -1) 
    {
        fprintf(stderr, "listen error:%s\n\a", strerror(errno));
        exit(1);
    }
    return 0;
}
/**
 * Helper function to resolve a listening.
 * @param runp information about the socket to try not
 * @return the opened socket or INVALID_SOCKET
 */
static SOCKET ListenLoopProc(addrinfo *runp)
{
	const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
	const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
	const char *address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();

	SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
	if (sock == INVALID_SOCKET) {
		DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, strerror(errno));
		return INVALID_SOCKET;
	}

	if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
		DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
	}

	int on = 1;
	/* The (const char*) cast is needed for windows!! */
	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
		DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, strerror(errno));
	}

	if (runp->ai_family == AF_INET6 &&
			setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
		DEBUG(net, 3, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, strerror(errno));
	}

	if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
		DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, strerror(errno));
		closesocket(sock);
		return INVALID_SOCKET;
	}

	if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
		DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, strerror(errno));
		closesocket(sock);
		return INVALID_SOCKET;
	}

	/* Connection succeeded */
	if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);

	DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
	return sock;
}
CSocket::CSocket(lua_State *luaVM, const string& strHost, const unsigned short& usPort)
{
    // Prepare variables
    m_bConnected = false;
    m_strHost    = strHost;
    m_usPort     = usPort;
    m_pLuaVM     = luaVM;
    m_pUserdata  = NULL;
    m_pSocket    = ERR_INVALID_SOCKET;
    
    // Prepare data for connection (cancel on failure)
    if (!ProcessTargetLocation(strHost, usPort))
        return;
    
    // Create the socket, and put it in non-blocking mode
    m_pSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // Exit if the socket failed to create
    if (m_pSocket == ERR_INVALID_SOCKET)
        return;

    ms_iTotalOpenSocketCount++;

    // Set the socket to non-blocking mode
    SetNonBlocking();

    // Make the socket connect
    if (connect(m_pSocket, (sockaddr*)&m_sSockAddr, sizeof(m_sSockAddr)) != ERR_CONNECT_SUCCESS)
    {
        // If the connection failed, check why
        int iError = GetLastSocketError();

        // If the error is ERR_WOULD_BLOCK (meaning it's in progress) then ignore
        if (iError != ERR_CONNECT_IN_PROGRESS)
        {
            // Error, so unload the socket and exit the function
            CloseSocket();
            return;
        }
    }

    // Create userdata, for identification
    m_pUserdata  = lua_newuserdata(luaVM, 128);
}
Example #27
0
bool
FileDescriptor::CreateInotify()
{
#ifdef __BIONIC__
  /* Bionic doesn't have inotify_init1() */
  int new_fd = inotify_init();
#else
  int new_fd = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
#endif
  if (new_fd < 0)
    return false;

#ifdef __BIONIC__
  SetNonBlocking();
#endif

  fd = new_fd;
  return true;
}
Example #28
0
bool SocketCom::Open()
{
	if (server)
	{
#ifdef TRACE
		printf("Opening server\n");
#endif
		Socket listener;
		if (!listener.Create()) return false;
#ifdef TRACE
		printf("Create OK\n");
#endif
		if (!listener.Bind(port)) return false;
#ifdef TRACE
		printf("Binding OK\n");
#endif
		if (!listener.Listen()) return false;
#ifdef TRACE
		printf("Listening OK\n");
#endif
		if (!listener.Accept(*this)) return false;
#ifdef TRACE
		printf("Accept OK\n");
#endif
	}
	else
	{
#ifdef TRACE
		printf("Opening client %s:%d\n",host,port);
#endif
		if (!Create()) return false;
#ifdef TRACE
	printf("Create OK\n");
#endif
		if (!Connect(host,port)) return false;
#ifdef TRACE
		printf("Connect OK\n");
#endif
		SetNonBlocking(true);
	}
	return true;
}
ClusterMembership::ClusterMembership(const IpAddress &bindaddr, const IpAddress &clusteraddr, int ifindex)
{
	// Set qhand to null initially
	qhand = 0;
	// Open multicast socket...
	sock = makesock(bindaddr);
	// Join multicast group(s)
	multisetup(sock, bindaddr, ifindex);
	// Make it nonblocking.
	SetNonBlocking(sock);
	this->clusteraddr = clusteraddr;
	this->localaddr = bindaddr;
	// Record the startup time
	gettimeofday(& starttime, 0);
	effectiveWeight = 0;
	// Add our own host to "nodes"
	nodes[bindaddr] = NodeInfo();
	nodes[bindaddr].isme = true;
	nodes[bindaddr].isup = true;
	nodes[bindaddr].weight = effectiveWeight;
}
Example #30
0
Bool
ConnectToRFBServer(const char *hostname, int port)
{
  unsigned int host;

  if (!StringToIPAddr(hostname, &host)) {
    fprintf(stderr,"Couldn't convert '%s' to host address\n", hostname);
    return False;
  }

// IPv6 change
  rfbsock = ConnectToTcpAddr(hostname, port);
  //rfbsock = ConnectToTcpAddr(host, port);

  if (rfbsock < 0) {
    fprintf(stderr,"Unable to connect to VNC server\n");
    return False;
  }

  return SetNonBlocking(rfbsock);
}