Ejemplo n.º 1
0
bool
Socket::connect( const std::string& IP, const int port, const int seconds, const int microseconds )
{
    if ( !isOpen() ) 
        return false;
    
    setNonBlocking(true);

    m_addr.sin_family = AF_INET;
    m_addr.sin_port = htons( port );
    
    // return 1 if ok, 0 id could not parse and -1 for error and errno set
    ::inet_pton(AF_INET, IP.c_str(), &m_addr.sin_addr);
    
    if ( errno == EAFNOSUPPORT ) 
        return false;
    
    bool retVal = true;
    
    // attempt a non-blocking connect
    // on error, -1 is returned, and errno is set appropriately;
    if (::connect(m_socket, (sockaddr *) &m_addr, sizeof(m_addr)) < 0) 
    { 
        retVal = false;
        if (errno == EINPROGRESS) 
        { 
            fd_set myset;
            FD_ZERO(&myset); // initialise file descriptor set
            FD_SET(m_socket, &myset); // set file descriptor set
            
            struct timeval tv;
            tv.tv_sec = seconds; 
            tv.tv_usec = microseconds; 
            
            // int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
            if (::select(m_socket + 1, NULL, &myset, NULL, &tv) > 0) 
            { 
                int errNum;
                socklen_t lon = sizeof(errNum); 
                
                // int getsockopt(int socket, int level, int optname, void *optval, socklen_t *optlen);
                if ((::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (void*)(&errNum), &lon) == 0) && (errNum == 0)) 
                    retVal = true;
            } 
        } 
    } 

    setNonBlocking(false);
    
    return retVal;
}
Ejemplo n.º 2
0
void SocketProxy::addSocketPair(int from,int to)
{
		// to simplify shutdown logic, dup any fds already in a socket pair
	if( fdInUse(from) ) {
		from = dup(from);
	}
	if( fdInUse(to) ) {
		to = dup(to);
	}
	m_socket_pairs.push_front(SocketProxyPair(from,to));
	if( !setNonBlocking(from) || !setNonBlocking(to) ) {
		setErrorMsg("Failed to set socket to non-blocking mode.");
	}
}
Ejemplo n.º 3
0
		// server functions
		bool listen( unsigned short port ) {
			if ( isConnected() ) {
				return false;
			}

			socket = ::socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
			if ( socket != INVALID_SOCKET ) {
				setBufferSizes( bufferSizeSend, bufferSizeRcv );
				setNonBlocking( nonBlocking );

				bool reuse = true;
				setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,(char*)&reuse,sizeof(reuse));

				int flag = 1;
				setsockopt(socket,IPPROTO_TCP,TCP_NODELAY,(char*)&flag,sizeof(int));

				sockaddr_in service;
				service.sin_family = AF_INET;
				service.sin_addr.s_addr = inet_addr("127.0.0.1");
				service.sin_port = htons(port);

				const int bindRes = ::bind( socket, (SOCKADDR*)&service, sizeof(service) );
				if ( bindRes != SOCKET_ERROR ) {
					const int listenRes = ::listen( socket, 1 );
					if ( listenRes != SOCKET_ERROR ) {
						return true;
					}
				}
				checkForDisconnectError();
			}
			return false;
		}
Ejemplo n.º 4
0
int BaseHandleThread::createListener(const std::string& host, int port, int backlog) {
    int listener = socket(AF_INET,SOCK_STREAM,0);
    if(listener < 0)
    {   
        ERROR_LOG("create socket error:%s", strerror(errno));
        return -1; 
    }   

    setNonBlocking(listener);
    reuseAddr(listener);

    struct sockaddr_in myaddr;
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons((unsigned short)port);
    myaddr.sin_addr.s_addr = inet_addr(host.c_str());

    if(bind(listener,(struct sockaddr*)&myaddr,sizeof(struct sockaddr)) < 0)
    {   
        close(listener);
        ERROR_LOG("bind ip:%s port:%d sock:%d err:%s",
                      host.c_str(),port,listener,strerror(errno));
        return -2; 
    }

    if(listen(listener, backlog) <0)
    {
        close(listener);
        ERROR_LOG("listen fd:%d err:%s",
                listener,strerror(errno));
        return -3;
    }

    return listener;
}
Ejemplo n.º 5
0
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: getNewConnection
--
-- DATE:		March 24, 2014
--
-- REVISIONS:	None
--
-- DESIGNER: 	Sam Youssef
--
-- PROGRAMMER:	Sam Youssef
--
-- INTERFACE:	int getNewConnection(int epollfd, int socklsn)
--
--									int epollfd: epoll file descriptor
--									int socklsn: the listening socket
--
--
-- RETURNS:	void.
--															
--
-- NOTES:
--
-- Handles new connections
--
-- Accepts an incoming connection. Calls accept(), which returns a new socket for receiving
-- Calls setNonBlocking() to sets the new socket to non-blocking mode
-- Adds the new socket to the epoll instance
------------------------------------------------------------------------------------------------------------------*/
int getNewConnection(int epollfd, int socklsn)
{	
	struct epoll_event 		event;
	struct sockaddr_in 		clientaddr;
	socklen_t 				clientaddrLen;
	int 					sockrcv;


	clientaddrLen = (socklen_t)sizeof(clientaddr);
	
	sockrcv = accept(socklsn, (struct sockaddr *)&clientaddr, &clientaddrLen);


	if(sockrcv == EAGAIN || sockrcv == EWOULDBLOCK) return 0;


	setNonBlocking (sockrcv);
	
	
	event . data.fd = sockrcv;
  	event . events  = EPOLLIN;
	
	epoll_ctl (epollfd, EPOLL_CTL_ADD, sockrcv, &event);
	return sockrcv;
}
Ejemplo n.º 6
0
void
setupNonBlockingTcpSocket(NTCP_State &state, const StaticString &hostname, int port) {
	int ret;

	memset(&state.hints, 0, sizeof(state.hints));
	state.hints.ai_family   = PF_UNSPEC;
	state.hints.ai_socktype = SOCK_STREAM;
	ret = getaddrinfo(hostname.toString().c_str(), toString(port).c_str(),
		&state.hints, &state.res);
	if (ret != 0) {
		string message = "Cannot resolve IP address '";
		message.append(hostname.data(), hostname.size());
		message.append(":");
		message.append(toString(port));
		message.append("': ");
		message.append(gai_strerror(ret));
		throw IOException(message);
	}

	state.fd = syscalls::socket(PF_INET, SOCK_STREAM, 0);
	if (state.fd == -1) {
		int e = errno;
		throw SystemException("Cannot create a TCP socket file descriptor", e);
	}

	state.hostname = hostname;
	state.port = port;
	setNonBlocking(state.fd);
}
Ejemplo n.º 7
0
UdpSock::UdpSock() :
Sock()
{
	handle = socket(AF_INET, SOCK_DGRAM, 17);
	assert(handle != INVALID_SOCKET);
	setNonBlocking();
}
Ejemplo n.º 8
0
ZL_SOCKET SocketUtil::createSocketAndListen(const char *ip, int port, int backlog)
{
    ZL_SOCKET sockfd = ZL_CREATE_SOCKET(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0) return sockfd;
    setNonBlocking(sockfd, true);

    ZL_SOCKADDR_IN  sockaddr;
    ::memset(&sockaddr, 0, sizeof(sockaddr));
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(port);
    int nIP = 0;
    if(!ip || '\0' == *ip || 0 == strcmp(ip, "0")
        || 0 == strcmp(ip, "0.0.0.0") || 0 == strcmp(ip, "*"))
    {
        nIP = htonl(INADDR_ANY);
    }
    else
    {
        nIP = inet_addr(ip);
    }
    sockaddr.sin_addr.s_addr = nIP;

    int res = ZL_BIND(sockfd, (struct sockaddr *) &sockaddr, sizeof(sockaddr));
    if(res < 0) return res;

    res = ZL_LISTEN(sockfd, backlog);
    if(res < 0) return res;

    return sockfd;
}
Ejemplo n.º 9
0
int Socket::accept(int fd){
	socklen_t len = sizeof(_address);
	_fd = ::accept(fd, (struct sockaddr *) &_address, &len);
	if (_fd == -1) return _fd;
	setNonBlocking(true);
	return _fd;
}
Ejemplo n.º 10
0
bool TransportTCP::initializeSocket()
{
  ROS_ASSERT(sock_ != ROS_INVALID_SOCKET);

  if (!setNonBlocking())
  {
    return false;
  }

  setKeepAlive(s_use_keepalive_, 60, 10, 9);

  // connect() will set cached_remote_host_ because it already has the host/port available
  if (cached_remote_host_.empty())
  {
    if (is_server_)
    {
      cached_remote_host_ = "TCPServer Socket";
    }
    else
    {
      std::stringstream ss;
      ss << getClientURI() << " on socket " << sock_;
      cached_remote_host_ = ss.str();
    }
  }

  if (local_port_ < 0)
  {
    la_len_ = s_use_ipv6_  ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
    getsockname(sock_, (sockaddr *)&local_address_, &la_len_);
    switch (local_address_.ss_family)
    {
      case AF_INET:
        local_port_ = ntohs(((sockaddr_in *)&local_address_)->sin_port);
        break;
      case AF_INET6:
        local_port_ = ntohs(((sockaddr_in6 *)&local_address_)->sin6_port);
        break;
    }
  }

#ifdef ROSCPP_USE_TCP_NODELAY
  setNoDelay(true);
#endif

  ROS_ASSERT(poll_set_ || (flags_ & SYNCHRONOUS));
  if (poll_set_)
  {
    ROS_DEBUG("Adding tcp socket [%d] to pollset", sock_);
    poll_set_->addSocket(sock_, boost::bind(&TransportTCP::socketUpdate, this, _1), shared_from_this());
  }

  if (!(flags_ & SYNCHRONOUS))
  {
    //enableRead();
  }

  return true;
}
Ejemplo n.º 11
0
bool Samurai::IO::Net::DatagramSocket::listen() {
    if (!addr || sd == INVALID_SOCKET) return false;
    if (!setReuseAddress(true)) return false;
    if (!setNonBlocking(true)) return false;
    if (!bind(addr)) return false;
    setMonitor(Samurai::IO::Net::SocketMonitor::MRead);
    return true;
}
Ejemplo n.º 12
0
/** Sets up fd callbacks. */
static void peerProxySetFd(PeerProxy* peerProxy, SelectableFd* fd) {
    peerProxy->fd = fd;
    fd->data = peerProxy;
    fd->onReadable = &peerProxyRead;
    fd->beforeSelect = &peerProxyBeforeSelect;
    
    // Make the socket non-blocking.
    setNonBlocking(fd->fd);
}
Ejemplo n.º 13
0
SocketBase::SocketBase(SOCKET fd, const Address &a)
    throw(NetworkException)
    : sockfd(fd), addr(a)
{
    state = CONNECTED;
    SocketManager::addSocket(this);
    setNonBlocking();
    disconnectTimer.setTimeOut(4000);
}
Ejemplo n.º 14
0
void
TCPSocket::onResolved()
{
    SocketBase::onResolved();
    create();
    setNonBlocking();
    setConfigured();
    doConnect();
    setNoDelay();
}
Ejemplo n.º 15
0
SocketFd  createSocketAndListen(const char *ip, short port, int backlog/* = 31*/)
{
    SocketFd sockfd = createSocket();
    if(sockfd < 0) return sockfd;

    setNonBlocking(sockfd, true);
    bind(sockfd, ip, port);
    listen(sockfd, backlog);
    return sockfd;
}
Ejemplo n.º 16
0
SocketBase::SocketBase(const Address &a, bool isTcp)
    throw(NetworkException)
    : addr(a)
{
    state = RESOLVED;
    create();
    setNonBlocking();
    disconnectTimer.setTimeOut(4000);
    state = CONFIGURED;
}
Ejemplo n.º 17
0
    bool SimpleHttpClient::connectSocket (struct addrinfo *aip) {

      // create socket and connect socket here
      
      _socket = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);

      // check socket and set the socket not blocking and close on exit 
      
      if (_socket == -1) {
        //setErrorMessage("Socket not connected. socket() faild with: " + string(strerror(errno)), errno);
        return false;
      }

      if (!setNonBlocking(_socket)) {
        //setErrorMessage("Socket not connected. Set non blocking failed with: " + string(strerror(errno)), errno);
        ::close(_socket);
        _socket = -1;
        return false;
      }

      if (!setCloseOnExec(_socket)) {
        //setErrorMessage("Socket not connected. Set close on exec failed with: " + string(strerror(errno)), errno);
        ::close(_socket);
        _socket = -1;
        return false;
      }

      ::connect(_socket, (const struct sockaddr *) aip->ai_addr, aip->ai_addrlen);

      struct timeval tv;
      fd_set fdset;

      tv.tv_sec = (uint64_t) _connectTimeout;
      tv.tv_usec = ((uint64_t) (_connectTimeout * 1000000.0)) % 1000000;

      FD_ZERO(&fdset);
      FD_SET(_socket, &fdset);

      if (select(_socket + 1, NULL, &fdset, NULL, &tv) > 0) {

        if (checkSocket()) {
          return true;
        }

        return false;
      }

      // connect timeout reached
      _errorMessage = "Could not conect to server in " + StringUtils::ftoa(_connectTimeout) + " seconds.";
      LOGGER_WARNING << "Could not conect to server in " << _connectTimeout << " seconds.";

      ::close(_socket);
      
      return false;
    }
Ejemplo n.º 18
0
bool
Socket::reconnect( const int seconds, const int microseconds )
{
    if ( !isOpen() ) 
        return false;
    
    setNonBlocking(true);
    
    bool retVal = true;
    
    // attempt a non-blocking connect
    // on error, -1 is returned, and errno is set appropriately;
    if (::connect(m_socket, (sockaddr *) &m_addr, sizeof(m_addr)) < 0) 
    { 
        retVal = false;
        if (errno == EINPROGRESS) 
        { 
            fd_set myset;
            FD_ZERO(&myset); // initialise file descriptor set
            FD_SET(m_socket, &myset); // set file descriptor set
            
            struct timeval tv;
            tv.tv_sec = seconds; 
            tv.tv_usec = microseconds;  
            
            // int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
            if (::select(m_socket + 1, NULL, &myset, NULL, &tv) > 0) 
            { 
                int errNum;
                socklen_t lon = sizeof(errNum); 
                
                // int getsockopt(int socket, int level, int optname, void *optval, socklen_t *optlen);
                if ((::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (void*)(&errNum), &lon) == 0) && (errNum == 0)) 
                    retVal = true;
            } 
        } 
    } 
    
    setNonBlocking(false);
    
    return retVal;
}
Ejemplo n.º 19
0
void Server::cleanup()
{
	NetworkBase::cleanup();

	if (serverSock_ != INVALID_SOCKET)
	{
		setNonBlocking(serverSock_, false);
		closesocket(serverSock_);
		serverSock_ = INVALID_SOCKET;
	}
}
Ejemplo n.º 20
0
void
setupNonBlockingUnixSocket(NUnix_State &state, const StaticString &filename) {
	state.fd = syscalls::socket(PF_UNIX, SOCK_STREAM, 0);
	if (state.fd == -1) {
		int e = errno;
		throw SystemException("Cannot create a Unix socket file descriptor", e);
	}

	state.filename = filename;
	setNonBlocking(state.fd);
}
Ejemplo n.º 21
0
void Epoll::addFd(int fd)
{
    struct epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN  ;
    if(enableET_)
    {
        event.events |= EPOLLET;
    }
    epoll_ctl(epollFd_,EPOLL_CTL_ADD,fd,&event);
    setNonBlocking(fd);
}
Ejemplo n.º 22
0
bool TSocket::createTCP( bool beNB )
{
	close();

	mSocketObj = ::socket( PF_INET , SOCK_STREAM , 0 );
	if ( mSocketObj  == INVALID_SOCKET )
	{
		throw SocketException("Can't create socket");
	}

	setNonBlocking( beNB );
	return true;
}
Ejemplo n.º 23
0
static int8_t registerEntity(dispatcher_t* disp,
		entity_context_t* ent_context) {

	pthread_mutex_lock(&(disp->disp_state));
	int32_t ret = 0;
	if (ent_context->fd >= disp->fd_lk->max_fds) {
		ret = -1;
		goto disp_unlock;
	}
	if (disp->fd_flag[ent_context->fd] == -1) {
		int8_t found_event = 0;
		int8_t found_timeout = 0;
		disp->fd_flag[ent_context->fd] = 1;
		disp->con_ptr[ent_context->fd] = ent_context;
		if ((ent_context->fd >= 0) && (ent_context->event_flags)) {
			if (addEvent(disp, ent_context, 
						ent_context->event_flags) < 0) {
				ret = -2;
				goto reg_error;
			}
			found_event = 1;
			setNonBlocking(ent_context->fd);
		}
		if ((ent_context->to_be_scheduled.tv_sec != 0) &&
				(ent_context->to_be_scheduled.tv_usec != 0)) {
			if (scheduleTimeoutEventLockHeld(disp,
						ent_context) < 0) {
				if (found_event == 1)
					delEvent(disp, ent_context, 
							ent_context->event_flags);
				ret = -2;
				goto reg_error;
			}
			found_timeout = 1;
		}
		if ((found_event == 1) || (found_timeout == 1)) {
			DBG_DISPLOG(DISP_MOD_NAME, DISP_MSG, disp_log_id, "Register success");
			ret = 1;
			goto disp_unlock;
		}
		ret = -3;
		goto reg_error;
	}
	ret = -4;
reg_error:
	disp->fd_flag[ent_context->fd] = -1;
	disp->con_ptr[ent_context->fd] = NULL;
disp_unlock:
	pthread_mutex_unlock(&(disp->disp_state));
	return ret;
}
Ejemplo n.º 24
0
Archivo: Os.c Proyecto: astaykov/ohNet
int32_t OsNetworkConnect(THandle aHandle, TIpAddress aAddress, uint16_t aPort, uint32_t aTimeoutMs)
{
    if ( OsNetworkHandle_IsInterrupted(aHandle) )
        return -1;
    
    LOGFUNCIN();

    struct sockaddr_in s;
    
    s.sin_family        = AF_INET;
    s.sin_port          = htons(aPort);
    s.sin_addr.s_addr   = aAddress;
    
    int err;
    
    setNonBlocking(aHandle, 1);
    
    err = lwip_connect ( HANDLE_TO_SOCKET(aHandle), (struct sockaddr*) &s, sizeof(s) );
    
    setNonBlocking(aHandle, 0);
    
    if ( err == 0 )
        return 0;
    
    if ( errno != EINPROGRESS )
    {
        // error!
        return -1;
    }
    
    if ( local_select(aHandle, LS_WRITE, aTimeoutMs) < 0 )
    {
        return -1;
    }
    
    LOGFUNCOUT();
    return 0;
}
Ejemplo n.º 25
0
Socket::Socket(int sockfd,int nonblocking)
{
	if (sockfd<0){
		this->sockfd=socket(AF_INET,SOCK_STREAM,0);
		if(this->sockfd<0){
			exit_on_error(errno,"failed to create socket");
		}
		if (nonblocking!=BLOCKING){
			setNonBlocking(this->sockfd);
		}
	}else{
		this->sockfd=sockfd;
	}
}
Ejemplo n.º 26
0
Socket Socket::accept(int nonblocking)
{
	struct sockaddr_in addr;
	socklen_t addr_length=sizeof(addr);
	
	int conn_sockfd=::accept(this->sockfd,(struct sockaddr*)&addr,&addr_length);
	if (conn_sockfd<0){
		exit_on_error(errno,"failed to accept connection");
	}

	if(nonblocking!=BLOCKING){
		setNonBlocking(conn_sockfd);
	}
	return Socket(conn_sockfd,nonblocking);
}
Ejemplo n.º 27
0
void ArcnetIO::enable( )
{
	if ( isEnabled_ ) return;

	// Create and bind to socket
	createSocket();
	bindDevToSocket();

	// Make socket non-blocking
	setNonBlocking(true);

	// Register our alarm signal handler so we can timeout bad reads
	signal(SIGALRM,sig_alrm);

	isEnabled_ = true;
}
Ejemplo n.º 28
0
bool TSocket::createUDP()
{
	close();
	mSocketObj = ::socket( PF_INET , SOCK_DGRAM , IPPROTO_UDP );

	if ( mSocketObj == INVALID_SOCKET )
	{
		throw SocketException("Can't create socket");
	}

	setNonBlocking( true );

	mState = SKS_UDP;

	return true;
}
Ejemplo n.º 29
0
Socket::Socket(sockaddr_in addr,int nonblocking)
{
	this->sockfd=socket(AF_INET,SOCK_STREAM,0);
	if (sockfd<0){
		exit_on_error(errno,"failed to create socket");
	}
	int on=1;
	setsockopt(this->sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
	if(bind(this->sockfd,(struct sockaddr*)&addr,sizeof(addr))!=0){
		exit_on_error(errno,"failed to bind socket");

	}
	if(nonblocking!=BLOCKING){
		setNonBlocking(this->sockfd);
	}

}
Ejemplo n.º 30
0
/**
 * Starts the master peer. The master peer differs from other peers in that
 * it is responsible for connecting the other peers. You can only have one
 * master peer.
 *
 * Goes into an I/O loop and does not return.
 */
void masterPeerInitialize(BytesListener* bytesListener, 
        DeathListener* deathListener) {
    // Create and bind socket.
    int listenerSocket = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (listenerSocket == -1) {
        LOG_ALWAYS_FATAL("socket() error: %s", strerror(errno));
    }
    unlink(MASTER_PATH);
    int result = bind(listenerSocket, (SocketAddress*) getMasterAddress(), 
            sizeof(UnixAddress));
    if (result == -1) {
        LOG_ALWAYS_FATAL("bind() error: %s", strerror(errno));
    }

    ALOGD("Listener socket: %d",  listenerSocket);
    
    // Queue up to 16 connections.
    result = listen(listenerSocket, 16);
    if (result != 0) {
        LOG_ALWAYS_FATAL("listen() error: %s", strerror(errno));
    }

    // Make socket non-blocking.
    setNonBlocking(listenerSocket);

    // Create the peer for this process. Fail if we already have one.
    if (localPeer != NULL) {
        LOG_ALWAYS_FATAL("Peer is already initialized.");
    }
    localPeer = peerCreate();
    if (localPeer == NULL) {
        LOG_ALWAYS_FATAL("malloc() failed.");
    }
    localPeer->master = true;
    localPeer->onBytes = bytesListener;
    localPeer->onDeath = deathListener;
    
    // Make listener socket selectable.
    SelectableFd* listenerFd = selectorAdd(localPeer->selector, listenerSocket);
    if (listenerFd == NULL) {
        LOG_ALWAYS_FATAL("malloc() error.");
    }
    listenerFd->data = localPeer;
    listenerFd->onReadable = &masterAcceptConnection;
}