Beispiel #1
0
void CNetworkConnection::connectToHost(IPv4_ENDPOINT oAddress)
{
    QHostAddress hostAddr(oAddress.ip);
    m_oAddress = oAddress;
    m_bInitiated = true;
    m_bConnected = false;
    m_tConnected = time(0);

    Q_ASSERT(m_pInput == 0);
    Q_ASSERT(m_pOutput == 0);
    m_pInput = new QByteArray();
    m_pOutput = new QByteArray();
    Q_ASSERT(m_pSocket == 0);

	m_pSocket = new QTcpSocket();
    initializeSocket();

    //m_pSocket->connectToHost(hostAddr, m_oAddress.port);
    QTcpSocket::connectToHost(hostAddr, m_oAddress.port);
    /*qDebug() << "connectToHost - object dump";
    m_pSocket->dumpObjectInfo();
    dumpObjectInfo();
    qDebug() << "--- end of dump ---";*/

}
bool TransportUDP::createIncoming(int port, bool is_server)
{
  is_server_ = is_server;

  sock_ = socket(AF_INET, SOCK_DGRAM, 0);

  if (sock_ <= 0)
  {
    ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
    return false;
  }

  server_address_.sin_family = AF_INET;
  server_address_.sin_port = htons(port);
  server_address_.sin_addr.s_addr = INADDR_ANY;
  if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
  {
    ROS_ERROR("bind() failed with error [%s]",  last_socket_error_string());
    return false;
  }

  socklen_t len = sizeof(server_address_);
  getsockname(sock_, (sockaddr *)&server_address_, &len);
  server_port_ = ntohs(server_address_.sin_port);
  ROSCPP_LOG_DEBUG("UDPROS server listening on port [%d]", server_port_);

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

  enableRead();

  return true;
}
Beispiel #3
0
CdSocket::CdSocket(unsigned short status, string server_address,unsigned short tcp_port){
	this->status = status;
	this->serv_host_addr = server_address;
	this->serv_tcp_port = tcp_port;

	initializeSocket();
}
void CNetworkConnection::AttachTo(CNetworkConnection* pOther)
{
	Q_ASSERT(m_pSocket == 0);
	m_pSocket = pOther->m_pSocket;
	pOther->m_pSocket = 0;

	m_bConnected = pOther->m_bConnected;
	m_tConnected = pOther->m_tConnected;
	m_bInitiated = pOther->m_bInitiated;

	Q_ASSERT(m_pInput == 0);
	Q_ASSERT(m_pOutput == 0);
	m_pInput = pOther->m_pInput;
	m_pOutput = pOther->m_pOutput;
	pOther->m_pInput = pOther->m_pOutput = 0;

	if( m_pSocket->peerAddress().protocol() == 0 )
	{
		m_oAddress.setAddress(m_pSocket->peerAddress().toIPv4Address());
	}
	else
	{
		m_oAddress.setAddress(m_pSocket->peerAddress().toIPv6Address());
	}
	m_oAddress.setPort(m_pSocket->peerPort());

	initializeSocket();

	if(!m_bReadyReadSent)
	{
		m_bReadyReadSent = true;
		emit readyRead();
	}

}
void CNetworkConnection::AcceptFrom(int nHandle)
{
	Q_ASSERT(m_pSocket == 0);
	m_pSocket = new QTcpSocket();

	initializeSocket();

	m_bInitiated = false;
	m_bConnected = true;
	m_tConnected = time(0);

	Q_ASSERT(m_pInput == 0);
	Q_ASSERT(m_pOutput == 0);
	m_pInput = new CBuffer(8192);
	m_pOutput = new CBuffer(8192);

	m_pSocket->setSocketDescriptor(nHandle);
	if( m_pSocket->peerAddress().protocol() == 0 )
	{
		m_oAddress.setAddress(m_pSocket->peerAddress().toIPv4Address());
	}
	else
	{
		m_oAddress.setAddress(m_pSocket->peerAddress().toIPv6Address());
	}
	m_oAddress.setPort(m_pSocket->peerPort());

	emit readyToTransfer();

}
UdpTransmitSocket& SoundplaneOSCOutput::getTransmitSocketForOffset(int portOffset)
{
	if(!mSocketInitialized[portOffset])
	{
		initializeSocket(portOffset);
	}
	return *mUDPSockets[portOffset];
}
static void onInitialize(JvmHeapScanInterfaces intfs)
{
	msgStore = intfs.msgStore;
	syncInterface = intfs.syncInterface;
	jvmFunctions = intfs.jvmFunctions;
	initializeSocket(intfs.agentOptions.port);
	statusLock = CreateEvent(NULL, TRUE, FALSE, NULL);
}
osc::OutboundPacketStream& SoundplaneOSCOutput::getPacketStreamForOffset(int portOffset)
{
	if(!mSocketInitialized[portOffset])
	{
		initializeSocket(portOffset);
	}
	osc::OutboundPacketStream& p (*mUDPPacketStreams[portOffset]);
	p.Clear();
	return p;
}
Beispiel #9
0
    /**
     * Name:        beginServer
     * Description: Binds a socket and begins listening to it for the web server.
     *
     * @param ipaddress  IP Address
     * @param port       Port Number
     */
void beginServer(const char* ipaddress, const char * port) {

    //initialize the socket
    int sock = initializeSocket(ipaddress, port);

    if(sock < 0) {
        endServer(sock, NULL, 0);
    }

    runServer(sock);
}
Beispiel #10
0
Qt4NodeInstanceClientProxy::Qt4NodeInstanceClientProxy(QObject *parent) :
    NodeInstanceClientProxy(parent)
{
    if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
        setNodeInstanceServer(new Qt4PreviewNodeInstanceServer(this));
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
        setNodeInstanceServer(new Qt4InformationNodeInstanceServer(this));
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("rendermode")) {
        setNodeInstanceServer(new Qt4RenderNodeInstanceServer(this));
    }

    initializeSocket();
}
Qt5NodeInstanceClientProxy::Qt5NodeInstanceClientProxy(QObject *parent) :
    NodeInstanceClientProxy(parent)
{
    prioritizeDown();
    DesignerSupport::activateDesignerWindowManager();
    if (QCoreApplication::arguments().at(1) == QLatin1String("--readcapturedstream")) {
        qputenv("DESIGNER_DONT_USE_SHARED_MEMORY", "1");
        setNodeInstanceServer(new Qt5TestNodeInstanceServer(this));
        initializeCapturedStream(QCoreApplication::arguments().at(2));
        readDataStream();
        QCoreApplication::exit();
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
        setNodeInstanceServer(new Qt5PreviewNodeInstanceServer(this));
        initializeSocket();
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
        setNodeInstanceServer(new Qt5InformationNodeInstanceServer(this));
        initializeSocket();
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("rendermode")) {
        setNodeInstanceServer(new Qt5RenderNodeInstanceServer(this));
        initializeSocket();
    }
}
Qt5NodeInstanceClientProxy::Qt5NodeInstanceClientProxy(QObject *parent) :
    NodeInstanceClientProxy(parent)
{
    DesignerSupport::activateDesignerWindowManager();
    if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
        setNodeInstanceServer(new Qt5PreviewNodeInstanceServer(this));
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
        setNodeInstanceServer(new Qt5InformationNodeInstanceServer(this));
    } else if (QCoreApplication::arguments().at(2) == QLatin1String("rendermode")) {
        setNodeInstanceServer(new Qt5RenderNodeInstanceServer(this));
    }

    initializeSocket();
}
void CNetworkConnection::ConnectTo(CEndPoint oAddress)
{
	m_oAddress = oAddress;

	m_bInitiated = true;
	m_bConnected = false;
	m_tConnected = time(0);

	Q_ASSERT(m_pInput == 0);
	Q_ASSERT(m_pOutput == 0);
	m_pInput = new CBuffer(8192);
	m_pOutput = new CBuffer(8192);
	Q_ASSERT(m_pSocket == 0);

	m_pSocket = new QTcpSocket();
	initializeSocket();
	m_pSocket->connectToHost(oAddress, oAddress.port());

}
Beispiel #14
0
bool UDP_Socket::initialize(unsigned int port)
{
	if (!initializeSocket())
	{
		printf("Unable to start the socket!\n");
		return false;
	}
	if (!createSocket(port))
	{
		printf("Unable to create the socket!\n");
		return false;
	}
	if (!makeSocketNonBlocking())
	{
		printf("Unable to make socket not block!\n");
		return false;
	}
	//This is old and will need to be depricated.
	serializedPacketHeaderSize = sizeof(uint32_t) * NUM_PACKET_UINT32 + sizeof(uint16_t) * NUM_PACKET_UINT16 + sizeof(uint8_t) * NUM_PACKET_UINT8;
	return true;
}
bool TransportTCP::listen(int port, int backlog, const AcceptCallback& accept_cb)
{
    is_server_ = true;
    accept_cb_ = accept_cb;

    sock_ = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_ <= 0)
    {
        ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
        return false;
    }

    server_address_.sin_family = AF_INET;
    server_address_.sin_port = htons(port);
    server_address_.sin_addr.s_addr = INADDR_ANY;
    if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
    {
        ROS_ERROR("bind() failed with error [%s]", last_socket_error_string());
        return false;
    }

    ::listen(sock_, backlog);
    socklen_t len = sizeof(server_address_);
    getsockname(sock_, (sockaddr *)&server_address_, &len);
    server_port_ = ntohs(server_address_.sin_port);

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

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

    return true;
}
Beispiel #16
0
void CNetworkConnection::AttachTo(QTcpSocket *pOther)
{
    Q_ASSERT(m_pSocket == 0);
    m_pSocket = pOther;
    m_pSocket->disconnect();

    m_bConnected = true;
    m_tConnected = time(0);
    m_bInitiated = false;

    Q_ASSERT(m_pInput == 0);
    Q_ASSERT(m_pOutput == 0);
    m_pInput = new QByteArray();
    m_pOutput = new QByteArray();

    m_oAddress.ip = m_pSocket->peerAddress().toIPv4Address();
    m_oAddress.port = m_pSocket->peerPort();

    initializeSocket();
    //GetInputBuffer()->append(pOther->readAll());
    //emit readyToTransfer();
}
	NetworkingObject::NetworkingObject()
		:	m_bytesQueued( 0 )
		,	iResult( 0 )
		,	m_currentPacket( nullptr )
		,	m_socket( INVALID_SOCKET )
		,	m_currentCommand( CMD_NONE )
		,	m_messageIndex( 0 )
		,	m_bytesReceived( 0 )
	{
		//m_bufferSize = sizeof( NetworkPacket );
		m_bufferSize = 4096;			//This is = to .5 kb
		m_receivedData = new char[ m_bufferSize ];
		m_messageBuffer.reserve( m_bufferSize );

		//m_currentPacket = new( m_buffer ) NetworkPacket();
		//m_buffer and m_currentPacket both point to the same location in memory

		m_senderAddressSize = sizeof( m_senderAddress );
		initializeSocket();

		outputFile.open ("test.txt", std::ofstream::out | std::ofstream::app);
		outputFile <<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
	}
bool TransportTCP::connect(const std::string& host, int port)
{
    sock_ = socket(AF_INET, SOCK_STREAM, 0);
    connected_host_ = host;
    connected_port_ = port;

    if (sock_ == ROS_INVALID_SOCKET)
    {
        ROS_ERROR("socket() failed with error [%s]",  last_socket_error_string());
        return false;
    }

    setNonBlocking();

    sockaddr_in sin;
    sin.sin_family = AF_INET;
    if (inet_addr(host.c_str()) == INADDR_NONE)
    {
        struct addrinfo* addr;
        if (getaddrinfo(host.c_str(), NULL, NULL, &addr) != 0)
        {
            close();
            ROS_ERROR("couldn't resolve publisher host [%s]", host.c_str());
            return false;
        }

        bool found = false;
        struct addrinfo* it = addr;
        for (; it; it = it->ai_next)
        {
            if (it->ai_family == AF_INET)
            {
                memcpy(&sin, it->ai_addr, it->ai_addrlen);
                sin.sin_family = it->ai_family;
                sin.sin_port = htons(port);

                found = true;
                break;
            }
        }

        freeaddrinfo(addr);

        if (!found)
        {
            ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
            return false;
        }

        ROSCPP_LOG_DEBUG("Resolved publisher host [%s] to [%s] for socket [%d]", host.c_str(), inet_ntoa(sin.sin_addr), sock_);
    }
    else
    {
        sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
    }

    sin.sin_port = htons(port);

    int ret = ::connect(sock_, (sockaddr *)&sin, sizeof(sin));
    // windows might need some time to sleep (input from service robotics hack) add this if testing proves it is necessary.
    ROS_ASSERT((flags_ & SYNCHRONOUS) || ret != 0);
    if (((flags_ & SYNCHRONOUS) && ret != 0) || // synchronous, connect() should return 0
            (!(flags_ & SYNCHRONOUS) && last_socket_error() != ROS_SOCKETS_ASYNCHRONOUS_CONNECT_RETURN)) // asynchronous, connect() should return -1 and WSAGetLastError()=WSAEWOULDBLOCK/errno=EINPROGRESS
    {
        ROSCPP_LOG_DEBUG("Connect to tcpros publisher [%s:%d] failed with error [%d, %s]", host.c_str(), port, ret, last_socket_error_string());
        close();

        return false;
    }

    std::stringstream ss;
    ss << host << ":" << port << " on socket " << sock_;
    cached_remote_host_ = ss.str();

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

    if (flags_ & SYNCHRONOUS)
    {
        ROSCPP_LOG_DEBUG("connect() succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
    }
    else
    {
        ROSCPP_LOG_DEBUG("Async connect() in progress to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
    }

    return true;
}
Beispiel #19
0
void startServer(int portnum){

	struct sockaddr_in clientAddr; // client socket informations
	socklen_t clientAddrLen; // client socket address length

	// initialize size of struct
	clientAddrLen = sizeof(struct sockaddr_in);

	//clear junk values
	memset(&clientAddr,0,clientAddrLen);

	if((gI_socketFd = initializeSocket(portnum))==-1){
		perror("Initialize socket");
		return;
	}

	fprintf(stderr,"[%ld]MainServer initialized socket\n",(long)gPid_server);

	// create a semafor to control writing sequential to pipe
	sem_unlink(PIPE_CONTROL_SEM);
	getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1); 

	pipe(gPipe_cwpr);
	pipe(gPipe_crpw);
	// TODO : check pipe errors

	pthread_t th_pipeListener;
	pthread_create(&th_pipeListener,NULL,listenPipe,NULL);

	memset(&serverList,0,sizeof(hmlist_t)); //clear junks
	gettimeofday(&endTime,NULL);
	diffTime = getTimeDif(startTime,endTime);
	printf("[%ld]MainServer is builded in %ld ms\n",(long)gPid_server,diffTime);

	hmServData_t miniServer;
	
	pid_t pidChild=-1;
	pid_t pidClient=-1;

	while(!doneflag){

		printf("[%ld]MainServer waiting for clients...\n",(long)gPid_server);
		// accept clients
		fdClient = accept(gI_socketFd,(struct sockaddr*)&clientAddr,&clientAddrLen);
		if(fdClient !=-1 && !doneflag){
			// client send pid address and server creates new mini server to serv
			read(fdClient,&pidClient,sizeof(pid_t));
			if( (pidChild = fork())==-1){
				perror("Fork");
				doneflag=1;
			}else if(pidChild==0){ // child here
				break;
			}else{ // parent here
				// pair server-client informations
				memset(&miniServer,0,sizeof(hmServData_t));
				miniServer.pidServer=pidChild;
				miniServer.pidClient=pidClient;
				miniServer.fdSocket = fdClient;
				addList(&serverList,&miniServer); // store child informations
				gettimeofday(&endTime,NULL);
				diffTime = getTimeDif(startTime,endTime);
				printf("Client[%ld] connected to server[%ld] in %ld ms\n",
	 									(long)pidClient,(long)pidChild,diffTime);
			}
		}else doneflag=1;
	}

	if(pidChild ==0){ // child here
		// no need to re-open semafor because we forked all memory
		/*sem_close(gSemP_pipeSem);
		getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1);*/
		gPid_server = getpid(); // assing new mini server pid
		deleteList(&serverList); // remove parent values
		startMiniServer(pidClient); // start server
		pthread_join(th_pipeListener,NULL);
		sem_close(gSemP_pipeSem);
		close(gI_socketFd); // close spesific socket fildes
		// return main and close mini server
	}else{ // main server here
		killAllChilds(SIGINT); 
		close(gPipe_cwpr[1]); //close pipe to kill thread

		while(wait(NULL)!=-1){} // wait childs
		// TODO : create thread to wait childs
		deleteList(&serverList);
		printf("[%ld]MainServer Waiting for threads\n",(long)gPid_server);
		pthread_join(th_pipeListener,NULL);
		sem_close(gSemP_pipeSem);
		close(gI_socketFd);
	}
}
Beispiel #20
0
bool TransportTCP::setSocket(int sock)
{
  sock_ = sock;
  return initializeSocket();
}
Beispiel #21
0
bool TransportTCP::listen(int port, int backlog, const AcceptCallback& accept_cb)
{
  is_server_ = true;
  accept_cb_ = accept_cb;

  if (s_use_ipv6_)
  {
    sock_ = socket(AF_INET6, SOCK_STREAM, 0);
    sockaddr_in6 *address = (sockaddr_in6 *)&server_address_;
    address->sin6_family = AF_INET6;
    address->sin6_addr = isOnlyLocalhostAllowed() ? 
                         in6addr_loopback : 
                         in6addr_any;
    address->sin6_port = htons(port);
    sa_len_ = sizeof(sockaddr_in6);
  }
  else
  {
    sock_ = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in *address = (sockaddr_in *)&server_address_;
    address->sin_family = AF_INET;
    address->sin_addr.s_addr = isOnlyLocalhostAllowed() ? 
                               htonl(INADDR_LOOPBACK) : 
                               INADDR_ANY;
    address->sin_port = htons(port);
    sa_len_ = sizeof(sockaddr_in);
  }

  if (sock_ <= 0)
  {
    ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
    return false;
  }


  if (bind(sock_, (sockaddr *)&server_address_, sa_len_) < 0)
  {
    ROS_ERROR("bind() failed with error [%s]", last_socket_error_string());
    return false;
  }

  ::listen(sock_, backlog);
  getsockname(sock_, (sockaddr *)&server_address_, &sa_len_);

  switch (server_address_.ss_family)
  {
    case AF_INET:
      server_port_ = ntohs(((sockaddr_in *)&server_address_)->sin_port);
      break;
    case AF_INET6:
      server_port_ = ntohs(((sockaddr_in6 *)&server_address_)->sin6_port);
      break;
  }

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

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

  return true;
}
Beispiel #22
0
bool TransportTCP::connect(const std::string& host, int port)
{
  if (!isHostAllowed(host))
    return false; // adios amigo

  sock_ = socket(s_use_ipv6_ ? AF_INET6 : AF_INET, SOCK_STREAM, 0);
  connected_host_ = host;
  connected_port_ = port;

  if (sock_ == ROS_INVALID_SOCKET)
  {
    ROS_ERROR("socket() failed with error [%s]",  last_socket_error_string());
    return false;
  }

  setNonBlocking();

  sockaddr_storage sas;
  socklen_t sas_len;

  in_addr ina;
  in6_addr in6a;
  if (inet_pton(AF_INET, host.c_str(), &ina) == 1)
  {
    sockaddr_in *address = (sockaddr_in*) &sas;
    sas_len = sizeof(sockaddr_in);
    
    la_len_ = sizeof(sockaddr_in);
    address->sin_family = AF_INET;
    address->sin_port = htons(port);
    address->sin_addr.s_addr = ina.s_addr;
  }
  else if (inet_pton(AF_INET6, host.c_str(), &in6a) == 1)
  {
    sockaddr_in6 *address = (sockaddr_in6*) &sas;
    sas_len = sizeof(sockaddr_in6);
    la_len_ = sizeof(sockaddr_in6);
    address->sin6_family = AF_INET6;
    address->sin6_port = htons(port);
    memcpy(address->sin6_addr.s6_addr, in6a.s6_addr, sizeof(in6a.s6_addr));
  }
  else
  {
    struct addrinfo* addr;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;

    if (getaddrinfo(host.c_str(), NULL, &hints, &addr) != 0)
    {
      close();
      ROS_ERROR("couldn't resolve publisher host [%s]", host.c_str());
      return false;
    }

    bool found = false;
    struct addrinfo* it = addr;
    char namebuf[128];
    for (; it; it = it->ai_next)
    {
      if (!s_use_ipv6_ && it->ai_family == AF_INET)
      {
        sockaddr_in *address = (sockaddr_in*) &sas;
        sas_len = sizeof(*address);
        
        memcpy(address, it->ai_addr, it->ai_addrlen);
        address->sin_family = it->ai_family;
        address->sin_port = htons(port);
	
        strcpy(namebuf, inet_ntoa(address->sin_addr));
        found = true;
        break;
      }
      if (s_use_ipv6_ && it->ai_family == AF_INET6)
      {
        sockaddr_in6 *address = (sockaddr_in6*) &sas;
        sas_len = sizeof(*address);
      
        memcpy(address, it->ai_addr, it->ai_addrlen);
        address->sin6_family = it->ai_family;
        address->sin6_port = htons((u_short) port);
      
        // TODO IPV6: does inet_ntop need other includes for Windows?
        inet_ntop(AF_INET6, (void*)&(address->sin6_addr), namebuf, sizeof(namebuf));
        found = true;
        break;
      }
    }

    freeaddrinfo(addr);

    if (!found)
    {
      ROS_ERROR("Couldn't resolve an address for [%s]\n", host.c_str());
      return false;
    }

    ROSCPP_LOG_DEBUG("Resolved publisher host [%s] to [%s] for socket [%d]", host.c_str(), namebuf, sock_);
  }

  int ret = ::connect(sock_, (sockaddr*) &sas, sas_len);
  // windows might need some time to sleep (input from service robotics hack) add this if testing proves it is necessary.
  ROS_ASSERT((flags_ & SYNCHRONOUS) || ret != 0);
  if (((flags_ & SYNCHRONOUS) && ret != 0) || // synchronous, connect() should return 0
      (!(flags_ & SYNCHRONOUS) && last_socket_error() != ROS_SOCKETS_ASYNCHRONOUS_CONNECT_RETURN)) // asynchronous, connect() should return -1 and WSAGetLastError()=WSAEWOULDBLOCK/errno=EINPROGRESS
  {
    ROSCPP_LOG_DEBUG("Connect to tcpros publisher [%s:%d] failed with error [%d, %s]", host.c_str(), port, ret, last_socket_error_string());
    close();

    return false;
  }

  // from daniel stonier:
#ifdef WIN32
  // This is hackish, but windows fails at recv() if its slow to connect (e.g. happens with wireless)
  // recv() needs to check if its connected or not when its asynchronous?
  Sleep(100);
#endif


  std::stringstream ss;
  ss << host << ":" << port << " on socket " << sock_;
  cached_remote_host_ = ss.str();

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

  if (flags_ & SYNCHRONOUS)
  {
    ROSCPP_LOG_DEBUG("connect() succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
  }
  else
  {
    ROSCPP_LOG_DEBUG("Async connect() in progress to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
  }

  return true;
}
Beispiel #23
0
bool TransportUDP::connect(const std::string& host, int port, int connection_id)
{
  if (!isHostAllowed(host))
    return false; // adios amigo

  sock_ = socket(AF_INET, SOCK_DGRAM, 0);
  connection_id_ = connection_id;

  if (sock_ == ROS_INVALID_SOCKET)
  {
    ROS_ERROR("socket() failed with error [%s]",  last_socket_error_string());
    return false;
  }

  sockaddr_in sin;
  sin.sin_family = AF_INET;
  if (inet_addr(host.c_str()) == INADDR_NONE)
  {
    struct addrinfo* addr;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;

    if (getaddrinfo(host.c_str(), NULL, &hints, &addr) != 0)
    {
      close();
      ROS_ERROR("couldn't resolve host [%s]", host.c_str());
      return false;
    }

    bool found = false;
    struct addrinfo* it = addr;
    for (; it; it = it->ai_next)
    {
      if (it->ai_family == AF_INET)
      {
        memcpy(&sin, it->ai_addr, it->ai_addrlen);
        sin.sin_family = it->ai_family;
        sin.sin_port = htons(port);

        found = true;
        break;
      }
    }

    freeaddrinfo(addr);

    if (!found)
    {
      ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
      return false;
    }

    ROSCPP_LOG_DEBUG("Resolved host [%s] to [%s]", host.c_str(), inet_ntoa(sin.sin_addr));
  }
  else
  {
    sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
  }

  sin.sin_port = htons(port);

  if (::connect(sock_, (sockaddr *)&sin, sizeof(sin)))
  {
    ROSCPP_LOG_DEBUG("Connect to udpros host [%s:%d] failed with error [%s]", host.c_str(), port,  last_socket_error_string());
    close();

    return false;
  }

  // from daniel stonier:
#ifdef WIN32
  // This is hackish, but windows fails at recv() if its slow to connect (e.g. happens with wireless)
  // recv() needs to check if its connected or not when its asynchronous?
  Sleep(100);
#endif

  std::stringstream ss;
  ss << host << ":" << port << " on socket " << sock_;
  cached_remote_host_ = ss.str();

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

  ROSCPP_LOG_DEBUG("Connect succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);

  return true;
}
bool TransportUDP::connect(const std::string& host, int port, int connection_id)
{
  sock_ = socket(AF_INET, SOCK_DGRAM, 0);
  connection_id_ = connection_id;

  if (sock_ == ROS_INVALID_SOCKET)
  {
    ROS_ERROR("socket() failed with error [%s]",  last_socket_error_string());
    return false;
  }

  sockaddr_in sin;
  sin.sin_family = AF_INET;
  if (inet_addr(host.c_str()) == INADDR_NONE)
  {
    struct addrinfo* addr;
    if (getaddrinfo(host.c_str(), NULL, NULL, &addr) != 0)
    {
      close();
      ROS_ERROR("couldn't resolve host [%s]", host.c_str());
      return false;
    }

    bool found = false;
    struct addrinfo* it = addr;
    for (; it; it = it->ai_next)
    {
      if (it->ai_family == AF_INET)
      {
        memcpy(&sin, it->ai_addr, it->ai_addrlen);
        sin.sin_family = it->ai_family;
        sin.sin_port = htons(port);

        found = true;
        break;
      }
    }

    freeaddrinfo(addr);

    if (!found)
    {
      ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
      return false;
    }

    ROSCPP_LOG_DEBUG("Resolved host [%s] to [%s]", host.c_str(), inet_ntoa(sin.sin_addr));
  }
  else
  {
    sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
  }

  sin.sin_port = htons(port);

  if (::connect(sock_, (sockaddr *)&sin, sizeof(sin)))
  {
    ROSCPP_LOG_DEBUG("Connect to udpros host [%s:%d] failed with error [%s]", host.c_str(), port,  last_socket_error_string());
    close();

    return false;
  }

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

  ROSCPP_LOG_DEBUG("Connect succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);

  return true;
}