Example #1
0
//don't use this one
//for server to use internally only!
//--------------------------
bool ofxTCPClient::setup(int _index, bool blocking){
	index = _index;

	//this fetches the port that the server
	//sets up the connection on
	//different to the server's listening port
	InetAddr addr;
	if( TCPClient.GetRemoteAddr(&addr) ){
		port   =  addr.GetPort();
		ipAddr =  addr.DottedDecimal();
	}

	TCPClient.SetNonBlocking(!blocking);
	connected 	= true;
	return true;
}
Example #2
0
void	InetAddr::set (const InetAddr &sa)
{
	if (sa.get_type () == -1)
		// Ugh, this is really a base class, so don't copy it.
		::memset (&this->inet_addr_, 0, sizeof (this->inet_addr_));
	else
	{
		// It's ok to make the copy.
		::memcpy (&this->inet_addr_,
	              &sa.inet_addr_,
	              sa.get_size ());

		this->set_type (sa.get_type());
		this->set_size (sa.get_size());
	}
}
Example #3
0
int		SocketConnector::connect(SocketStream &stream, InetAddr const &addr, size_t)
{
	Handle ret = ::connect(_handle, addr, addr.getSize());
	if (ret == INVALID_HANDLE)
		return -1;
	stream.setHandle(_handle);
	return 0;
}
Example #4
0
int Socket::accept(InetAddr &addr)
{
    struct sockaddr_in saddr;

    int connfd = acceptConn(fd_ , saddr);
    addr.setPureAddr(saddr);
    return connfd;
}
Example #5
0
bool NodeInfo::isReachable (const char **ppszInterfaces, NICInfo **ppNICInfos)
{
    InetAddrWrapper *pIfaceWr = _ipAddresses.getFirst();
    if (pIfaceWr == NULL || ppNICInfos == NULL) {
        return false;
    }
    do {
        for (int i = 0; ppNICInfos[i]; i++) {
            InetAddr addr (pIfaceWr->ifaceAddr.c_str());
            if (NetUtils::areInSameNetwork (ppNICInfos[i]->ip.s_addr, ppNICInfos[i]->netmask.s_addr,
                                            addr.getIPAddress(), ppNICInfos[i]->netmask.s_addr)) {
                return true;
            }
        }
    } while ((pIfaceWr = _ipAddresses.getNext()) != NULL);
    return false;
}
Example #6
0
ssize_t
SocketDgram::recv (void *buf,
              size_t n,
              InetAddr &addr,
              int flags) const {
  sockaddr* saddr = (sockaddr*)addr.getAddr();
  int addrlen = addr.getSize();

  ssize_t const status = OS::recvfrom(this->getHandle(),
                                      (char*)buf,
                                      n,
                                      flags,
                                      (sockaddr*)saddr,
                                      &addrlen);
  addr.setSize(addrlen);
  addr.setType(saddr->sa_family);
  return status;
}
Example #7
0
int Socket::connect(InetAddr& addr)
{
	assert(INVALID_SOCKET != fd_);
	
	int rst = ::connect(fd_, (struct sockaddr*)&addr.getNetAddr(), sizeof(sockaddr_in));
	if(-1 == rst)
		cout << "err: " << string(strerror(errno)) <<endl;
	
	return rst;
}
void OSConfigurator_linux24::addVirtualAddressForNAT(const Network *nw)
{
    FWOptions* options=fw->getOptionsObject();
    if (options->getBool("manage_virtual_addr"))
    {
        if (virtual_addresses.empty() || 
            find(virtual_addresses.begin(),virtual_addresses.end(),
                 *(nw->getAddressPtr())) == virtual_addresses.end())
        {
            Interface *iface = findInterfaceFor( nw, fw );
            if (iface!=nullptr)
            {
                const InetAddr *addr = nw->getAddressPtr();
                InetAddr first, last;
                InetAddr a;

                first = *addr;
                last = *(nw->getBroadcastAddressPtr());

                QStringList addresses;
                for (a=first; a<last; a=a+1)
                {
                    addresses.push_back(QString("%1/32").arg(a.toString().c_str()));
                }

                if (virtual_addresses_for_nat.count(iface->getName()) > 0)
                    addresses.push_front(virtual_addresses_for_nat[iface->getName()].c_str());

                virtual_addresses_for_nat[iface->getName()] =
                    addresses.join(" ").toStdString();

                virtual_addresses.push_back( *(nw->getAddressPtr()) );
                registerVirtualAddressForNat();
            } else
                warning("Can not add virtual address " +
                        nw->getAddressPtr()->toString() +
                        " (object " + nw->getName() + ")" );
        }
    }
}
Example #9
0
void TcpServer::onNewConnectionCallback(int fd, const InetAddr& addr)
{
    char buf[32];
    bzero((void*)buf, 32);
    std::string name = snprintf(buf, 32, "%s:%d",addr.getIpPortStr(),connectId_);
    logger::console->info("NewConnection:{}",name);
    ++connectId_;
    InetAddr localAddr(serverAddr_);
    TcpConnection* tcpConnection= new TcpConnection(name, eventloop_, fd, serverAddr_, addr);
    connectionMap_[name] = tcpConnection;
    tcpConnection->setCloseCallback(boost::bind(&TcpServer::removeConnection, this,_1));
    tcpConnection->setMessageCallback(messageCallback_);
    tcpConnection->setWriteCompleteCallback(writeCompleteCallback_);

}
Example #10
0
int StompConnection::connect(StompClient* client, const InetAddr& addr,
        const std::string& login, const std::string& passcode, const std::string& heartbeat)
{
    fd_ = Socket::create();
    if (fd_ < 0) {
        log_error("failed to create fd");
        return -1;
    }
    int ret = Socket::connect(fd_, addr);
    if (ret == 0) {
        state_ = ConnectionState::ESTABLISHED;
        evloop_->add_event(this, EV_READ);
    } else if (ret == EINPROGRESS) {
        state_ = ConnectionState::CONNECTING;
        evloop_->add_event(this, EV_READ|EV_WRITE);
    } else {
        log_error("fd: " << fd_ << " failed to connect addr: " << addr.to_string());
        return -1;
    }

    client_ = client;
    return 0;
}
MulticastJoinSpec::MulticastJoinSpec(const InetAddr &mcast,
                                     const InetInterface &inter) throw()
    : fam(mcast.family())
{
  if (fam != inter.family()) {
    fam = InetAddr::Invalid;
  } else {
    switch (fam) {
      case InetAddr::Invalid:
      default:
        // fam is already invalid - just leave it that way
        break;
      case InetAddr::IPv4:
        ipv4.imr_multiaddr = mcast;
        ipv4.imr_interface = inter.getIPv4Interface();
        break;
      case InetAddr::IPv6:
        ipv6.ipv6mr_multiaddr = mcast;
        ipv6.ipv6mr_interface = inter.getIPv6Interface();
        break;
    }
  }
}
int ProxyDatagramSocket::sendTo (uint32 ui32IPAddr, uint16 ui16Port, const void *pBuf, int iBufSize, const char *pszHints)
{
    int rc;
    if (_bConnectedToServer) {
        if (iBufSize < 0) {
            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_MildError,
                            "packet size cannot be negative\n");
            return -1;
        }
        if (iBufSize > (MAXIMUM_PROXY_PACKET_SIZE - 17)) {
            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_MildError,
                            "packet too large to be sent - maximum size is <%d>\n",
                            (int) (MAXIMUM_PROXY_PACKET_SIZE - 17));
            return -2;
        }
        try {
            bool bExcludeAddr = false;
            bool bIncludeAddr = false;
            InetAddr excludeAddr;
            InetAddr includeAddr;
            if (pszHints != NULL) {
                // Check to see if we can handle the hints
                StringTokenizer st (pszHints, ';');
                const char *pszHint = NULL;
                while ((pszHint = st.getNextToken()) != NULL) {
                    StringTokenizer st2 (pszHint, '=');
                    const char *pszAttr = st2.getNextToken();
                    const char *pszValue = st2.getNextToken();
                    if ((pszAttr == NULL) || (pszValue == NULL)) {
                        checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_Warning,
                                        "could not parse hint <%s> - ignoring\n", pszHint);
                    }
                    // Check to see if an exclude address has been specified in the hints
                    else if (0 == stricmp (pszAttr, "exclude")) {
                        if (InetAddr::isIPv4Addr (pszValue)) {
                            excludeAddr.setIPAddress (pszValue);
                            bExcludeAddr = true;
                        }
                        else {
                            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_Warning,
                                            "could not parse exclude address <%s> - ignoring\n", pszValue);
                        }
                    }
                    // Check to see if an include address has been specified in the hints
                    else if (0 == stricmp (pszAttr, "include")) {
                        if (InetAddr::isIPv4Addr (pszValue)) {
                            includeAddr.setIPAddress (pszValue);
                            bIncludeAddr = true;
                        }
                        else {
                            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_Warning,
                                            "could not parse include address <%s> - ignoring\n", pszValue);
                        }
                    }
                    // Check to see if we are doing a forced unicast
                    else if (0 == stricmp (pszAttr, "unicast")) {
                        if (InetAddr::isIPv4Addr (pszValue)) {
                            InetAddr unicastAddr (pszValue);
                            ui32IPAddr = unicastAddr.getIPAddress();
                            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_Info,
                                            "overwrote destination address with unicast address %s\n", unicastAddr.getIPAsString());
                        }
                    }
                    else {
                        checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_Warning,
                                        "unknown hint attribute <%s> - ignoring\n", pszAttr);
                    }
                }
            }
            /*!!*/ // Improve the efficiency of this by implementing a two-argument sendBlock() method
                   // so that a memcpy is not needed
            uint8 aui8Buf [MAXIMUM_PROXY_PACKET_SIZE];
            uint8 ui8Offset = 0;
            if (bIncludeAddr) {
                aui8Buf[ui8Offset] = 'I';
            }
            else if (bExcludeAddr) {
                aui8Buf[ui8Offset] = 'X';
            }
            else {
                aui8Buf[ui8Offset] = 'D';
            }
            ui8Offset += 1;
            (*((uint32*)(aui8Buf+ui8Offset))) = _ui32LocalAddr;
            ui8Offset += 4;
            (*((uint16*)(aui8Buf+ui8Offset))) = EndianHelper::htons (_ui16LocalPort);
            ui8Offset += 2;
            (*((uint32*)(aui8Buf+ui8Offset))) = ui32IPAddr;
            ui8Offset += 4;
            if (bIncludeAddr) {
                (*((uint32*)(aui8Buf+ui8Offset))) = includeAddr.getIPAddress();
                ui8Offset += 4;
            }
            else if (bExcludeAddr) {
                (*((uint32*)(aui8Buf+ui8Offset))) = excludeAddr.getIPAddress();
                ui8Offset += 4;
            }
            (*((uint16*)(aui8Buf+ui8Offset))) = EndianHelper::htons (ui16Port);
            ui8Offset += 2;
            memcpy (aui8Buf+ui8Offset, pBuf, iBufSize);
            _pchToServer->sendBlock (aui8Buf, iBufSize + ui8Offset);
            _ui32SentPacketCount++;
            return iBufSize;
        }
        catch (Exception e) {
            checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_MildError,
                            "exception occurred when sending data to proxy server; message = <%s>\n",
                            e.getMsg());
            close();
            rc = -3;
        }
    }
    else {
        checkAndLogMsg ("ProxyDatagramSocket::sendTo", Logger::L_MildError,
                        "cannot send - not connected to the proxy server\n");
        rc = -4;
    }
    connectToProxyServer();
    return rc;
}
Example #13
0
int
bindport(ACE_HANDLE handle, ACE_UINT32 ip_addr, int address_family) {
  InetAddr addr = InetAddr((u_short)0, ip_addr);
  return OS::bind(handle, (sockaddr*)addr.getAddr(), addr.getSize());
}
Example #14
0
bool NodeInfo::setIPAddress (uint32 ui32IpAddress)
{
    InetAddr addr (ui32IpAddress);
    return setIPAddress (addr.getIPAsString());
}
string PolicyCompiler_iosacl::PrintRule::_printAddr(Address  *o)
{
    PolicyCompiler_iosacl *iosacl_comp = dynamic_cast<PolicyCompiler_iosacl*>(compiler);
    if (Interface::cast(o)!=NULL)
    {
	Interface *interface_ = Interface::cast(o);
	if (interface_->isDyn())
        {
	    return string("interface ") + interface_->getLabel() + " ";
	}
    }

    ostringstream  str;

    const InetAddr *srcaddr = o->getAddressPtr();
    if (srcaddr)
    {
        const InetAddr *nm = o->getNetmaskPtr();
        InetAddr srcmask;

        if (nm != NULL)
        {
            srcmask = *nm;
        } else
        {
            cerr << "Address object "
                 << o
                 << " "
                 << o->getName()
                 << " (" << o->getTypeName() << ") "
                 << " has no netmask"
                 << endl;
            srcmask = InetAddr(InetAddr::getAllOnes(srcaddr->addressFamily()));
        }

//        const InetAddr srcmask = *(o->getNetmaskPtr());

        if (srcaddr->isAny() && srcmask.isAny())
        {
            str << "any  ";
        } else 
        {
            if (Interface::cast(o)==NULL &&
                Interface::cast(o->getParent())==NULL &&
                o->dimension() > 1 &&
                !srcmask.isHostMask())
            {
                if (iosacl_comp->ipv6)
                {
                    str << srcaddr->toString()
                        << "/"
                        << srcmask.getLength() << " ";
                } else
                {
                    str << srcaddr->toString() << " ";
                    // cisco uses "wildcards" instead of netmasks
                    //long nm = srcmask.to32BitInt();
                    //struct in_addr na;
                    //na.s_addr = ~nm;
                    InetAddr nnm( ~srcmask );
                    str << nnm.toString() << " ";                    
                }
            } else
            {
                str << "host " << srcaddr->toString() << " ";
            }
        }
        return str.str();
    }

    ostringstream errstr;
    errstr << "Object "
           << o->getName()
           << " (id="
           << o->getId()
           << ") "
           << " has no ip address and can not be used "
           << "in the rule.";
    compiler->abort(errstr.str());
    return "";  // to make compiler happy
}
Example #16
0
void Socket::bind(const InetAddr &addr)
{
    bindOn(fd_ , addr.getPeerAddr());
}
void NATCompiler_pf::PrintRule::_printAddr(FWObject *o)
{
    MultiAddressRunTime *atrt = MultiAddressRunTime::cast(o);
    if (atrt!=NULL)
    {
        if (atrt->getSubstitutionTypeName()==DNSName::TYPENAME)
        {
            compiler->output <<  atrt->getSourceName() << " ";
            return;
        }
        if (atrt->getSubstitutionTypeName()==AddressTable::TYPENAME)
        {
            compiler->output << "<" << o->getName() << "> ";
            return;
        }
        if (atrt->getSubstitutionTypeName()==AttachedNetworks::TYPENAME)
        {
            compiler->output << atrt->getSourceName() << ":network ";
            return ;
        }

        assert(atrt==NULL);
    }

    if (Interface::cast(o)!=NULL)
    {
        compiler->output << "(" << o->getName() << ") ";
        return;
    }

    if (o->getBool("pf_table"))
    {
        compiler->output << "<" << o->getName() << "> ";
        return;
    }

    Address *addr_obj = Address::cast(o);
    assert(addr_obj!=NULL);

    const InetAddr *addr = addr_obj->getAddressPtr();
    if (addr)
    {
        InetAddr mask = *(addr_obj->getNetmaskPtr());

        if (Interface::cast(o)!=NULL || Address::cast(o)->dimension()==1)
        {
            mask = InetAddr(InetAddr::getAllOnes());
        }

        if (addr->isAny() && mask.isAny())
        {
            compiler->output << "any ";
        } else
        {
            compiler->output << addr->toString();
            if (!mask.isHostMask())
            {
                compiler->output << "/" << mask.getLength();
            }
            compiler->output  << " ";
        }
    }
}
Example #18
0
string TableFactory::PrintTables()
{
    if (tables.size() == 0) return "";

    stringstream output;
    output << endl;
    output << "# Tables: (" << tables.size() << ")" << endl;

    for (map<string,string>::const_iterator i=tblnames.begin();
         i!=tblnames.end(); i++)
    {
        string tblID = i->second;
        FWObject *grp = tables[tblID];
        output << "table ";
        output << "<" << grp->getName() << "> ";
        MultiAddressRunTime *atrt = MultiAddressRunTime::cast(grp);
        if (atrt!=nullptr &&
            atrt->getSubstitutionTypeName()==AddressTable::TYPENAME)
        {
            output << "persist";
            if ( !atrt->getSourceName().empty() )
            {
                string path =
                    atrt->getSourceNameAsPath(firewall->getOptionsObject());
                if (path.empty()) {
                    compiler->abort("Error: Firewall's data directory not set for address table: " + atrt->getName());
                }
                
                output << " file \"" << path << "\"";
            }

            output << endl;
            continue;
        }
        output << "{ ";
        for (FWObject::iterator i=grp->begin(); i!=grp->end(); i++)
        {
            if (i!=grp->begin())  output << ", ";
            FWObject *o = FWReference::getObject(*i);
            if (o==nullptr) compiler->abort("broken table object ");

            MultiAddressRunTime *atrt = MultiAddressRunTime::cast(o);
            if (atrt!=nullptr)
            {
                if (atrt->getSubstitutionTypeName()==DNSName::TYPENAME)
                {
                    output <<  atrt->getSourceName() << " ";
                }
                if (atrt->getSubstitutionTypeName()==AttachedNetworks::TYPENAME)
                {
                    output << atrt->getSourceName() << ":network ";
                }
            } else
            {
                if (Interface::cast(o))
                {
                    output << o->getName();
                } else
                {
                    Address *A=Address::cast( o );
                    if (A==nullptr)
                        compiler->abort("table object must be an address: '" +
                                          o->getTypeName()+"'");

                    const InetAddr *addr = A->getAddressPtr();
                    InetAddr mask = *(A->getNetmaskPtr());

                    if (A->dimension()==1)
                    {
                        mask = InetAddr(InetAddr::getAllOnes());
                    }

                    output << addr->toString();
                    if (!mask.isHostMask())
                    {
                        output << "/" << mask.getLength();
                    }
                }
            }
            output << " ";
        }
        output << "} ";
        output << endl;
    }
    output << endl;
    return output.str();
}
Example #19
0
int PublisherHandler::handleInput(ACE_HANDLE fd) {
  if (msg == 0) {
    msg = new Msg;
  }

  int result = MsgProtocol::parse(&stream, msg);
  if (result == -1) {
    ICC_ERROR("PublisherHandler::handleInput error: %s", OS::strerror(OS::map_errno(OS::last_error())));
    delete msg;
    msg = 0;
    return -1;
  } else if (result == 1) {
    return 0;
  }

  assert(result == 0);

  if (msg->messageType == Msg_KeepAlive_Probe) {
    OutputStream os;
    MsgProtocol::start(Msg_KeepAlive_ACK, &os);
    std::string t("keepAlive");
    os.write_string(t);

    InetAddr peerAddr;
    this->getStream().getRemoteAddr(peerAddr);

//    ICC_DEBUG("recved publisher keep alive probe, sending ack, peer: %s", peerAddr.toString().c_str());
    int result = MsgProtocol::send(&this->getStream(), &os);
    if (result == 0) {
//      ICC_DEBUG("send keep alive probe ack succeeded, peer: %s", peerAddr.toString().c_str());
    }

    delete msg;
    msg = 0;
    return result;
  } else if(msg->messageType == Msg_Publish) {
    OutputStream os;
    MsgProtocol::start(Msg_Publish_OK, &os);
    os.write_string("publishOK");
    os.write_int(SubscriberHandler::keepAliveTryTimes);
    os.write_int(SubscriberHandler::keepAliveTimeSpan);
    os.write_boolean(SubscriberHandler::enableBuffering);

    InetAddr peerAddr;
    this->getStream().getRemoteAddr(peerAddr);

    ICC_DEBUG("sending Msg_Publish_OK, peer: %s", peerAddr.toString().c_str());
    result = MsgProtocol::send(&this->getStream(), &os);
    delete msg;
    msg = 0;
    return result;
  }

  assert(msg->messageType == Msg_Event);
  assert(msg->topic != "");

  // print log , temporary variable "type" is for info,
  string type;
  InputStream is(msg->is);
  is.read_string(type);
  ICC_DEBUG("recved publish event, topic: %s, type: %s", msg->topic.c_str(), type.c_str());

  if(SubscriberHandler::enableBuffering) {
    TopicManager::instance()->addMessage_(msg);
  } else {
    TopicManager::instance()->addMessage(msg, SubscriberHandler::enableBuffering);
  }
  msg = 0;

  return result;
}
void Connector::run (void)
{
    int rc;
    started();
    _pPDS->_bConnectedToServer = false;
    Socket *pSocketToServer = new TCPSocket();
    if (0 != (rc = ((TCPSocket*)pSocketToServer)->connect (_pPDS->_proxyServerAddr.getIPAsString(), _pPDS->_proxyServerAddr.getPort()))) {
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_Warning,
                        "failed to connect to proxy server at %s:%d\n",
                        _pPDS->_proxyServerAddr.getIPAsString(), (int) _pPDS->_proxyServerAddr.getPort());
        delete pSocketToServer;
        setTerminatingResultCode (-1);
        terminating();
        return;
    }
    checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_Info,
                    "connected to proxy server; LP:%d-RP:%d\n", pSocketToServer->getLocalPort(), pSocketToServer->getRemotePort());
    pSocketToServer->bufferingMode (0);
    CommHelper2 *pchToServer = new CommHelper2();
    if (0 != (rc = pchToServer->init (pSocketToServer))) {
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_MildError,
                        "failed to initialize CommHelper; rc = %d\n", rc);
        delete pchToServer;
        delete pSocketToServer;
        setTerminatingResultCode (-2);
        terminating();
        return;
    }
    InetAddr localAddr;
    uint16 ui16AssignedPort;
    uint16 ui16MTU;
    try {
        uint8 aui8Buf [ProxyDatagramSocket::MAXIMUM_PROXY_PACKET_SIZE];

        // Receive the Welcome message
        uint32 ui32PacketSize = pchToServer->receiveBlock (aui8Buf, ProxyDatagramSocket::MAXIMUM_PROXY_PACKET_SIZE);
        if ((ui32PacketSize < 1) || (aui8Buf[0] != 'w')) {
            throw ProtocolException ("expecting but did not receive a welcome message from server");
        }
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_MediumDetailDebug,
                        "connected to proxy server at %s:%d\n",
                        _pPDS->_proxyServerAddr.getIPAsString(), (int) _pPDS->_proxyServerAddr.getPort());
        if (ui32PacketSize > 2) {
            aui8Buf[ui32PacketSize] = '\0';      // Just for safety
            checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_MediumDetailDebug,
                            "proxy server identification string is <%s>\n",
                            (char*) aui8Buf+2);
        }

        // Receive the Address message
        ui32PacketSize = pchToServer->receiveBlock (aui8Buf, ProxyDatagramSocket::MAXIMUM_PROXY_PACKET_SIZE);
        if ((ui32PacketSize < 6) || (aui8Buf[0] != 'a')) {
            throw ProtocolException ("expecting but did not receive an address message from server");
        }
        if (aui8Buf[1] != 0) {
            if (aui8Buf[1] == 4) {
                // Received a 4-byte address - store it as the local address
                localAddr = InetAddr (*((uint32*)(aui8Buf+2)));
                checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_LowDetailDebug,
                                "set local address to %s (%x)\n",
                                localAddr.getIPAsString(), localAddr.getIPAddress());
            }
            else {
                checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_Warning,
                                "received a local address of length %d - ignoring since it is not a 4 byte address\n",
                                (int) aui8Buf[1]);
            }
        }

        // Receive the MTU message
        ui32PacketSize = pchToServer->receiveBlock (aui8Buf, ProxyDatagramSocket::MAXIMUM_PROXY_PACKET_SIZE);
        if ((ui32PacketSize < 3) || (aui8Buf[0] != 'm')) {
            throw ProtocolException ("expecting but did not receive an MTU message from server");
        }
        ui16MTU = EndianHelper::ntohs (*((uint16*)(aui8Buf+1)));
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_LowDetailDebug,
                        "set MTU to %d\n", (int) ui16MTU);

        // Send the bind message
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_LowDetailDebug,
                        "sending a bind message; local port = %d\n", _pPDS->_ui16LocalPort);
        aui8Buf[0] = 'B';
        (*((uint16*)(aui8Buf+1))) = EndianHelper::htons (_pPDS->_ui16LocalPort);
        pchToServer->sendBlock (aui8Buf, 3);

        // Receive the reply
        ui32PacketSize = pchToServer->receiveBlock (aui8Buf, ProxyDatagramSocket::MAXIMUM_PROXY_PACKET_SIZE);
        if ((ui32PacketSize < 3) || (aui8Buf[0] != 'b')) {
            throw ProtocolException ("expecting but did not receive a bind reply message from server");
        }
        ui16AssignedPort = EndianHelper::ntohs (*((uint16*)(aui8Buf+1)));

        if (ui16AssignedPort == 0) {
            throw ProtocolException ("server failed to assign a port");
        }

        _pPDS->_ui16LocalPort = ui16AssignedPort;
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_MediumDetailDebug,
                        "bound socket to local port <%d>\n",
                        (int) _pPDS->_ui16LocalPort);
    }
    catch (Exception e) {
        checkAndLogMsg ("[ProxyDatagramSocket]Connector::run", Logger::L_MildError,
                        "exception when establishing connection to proxy server; message = <%s>\n",
                        e.getMsg());
        delete pchToServer;
        delete pSocketToServer;
        this->setTerminatingResultCode (-3);
        terminating();
        return;
    }
    _pPDS->_pchToServer = pchToServer;
    _pPDS->_pSocketToServer = pSocketToServer;
    _pPDS->_ui16MTU = ui16MTU;
    _pPDS->_ui32LocalAddr = localAddr.getIPAddress();
    _pPDS->_ui16LocalPort = ui16AssignedPort;
    _pPDS->_bConnectedToServer = true;
    setTerminatingResultCode (0);
    terminating();
    return;
}
int udpServer (void)
{
    int rc; 
    uint32 ui32SeqNum;

    uint16 ui16ClientPort = 0;
    int lastSequenceNumber = -1;
    int numPacketsRecvd = 0;
    int numPacketsLost = 0;
    uint64 ui64FirstPacketTS = 0;
    uint64 ui64LastPacketTS = 0;
    uint64 ui64TotalBytesReceived = 0;

    int outOfOrderPackets = 0;

    while (true) {
        InetAddr clientAddr;
        // ui64LastPacketTS will be used when client port changes to calculate
        // how long it took to receive a chunk of data
        ui64LastPacketTS = getTimeInMilliseconds();
        if ((rc = dgSocket.receive (buf, sizeof (buf), &clientAddr)) <= 0) {
            fprintf (stderr, "failed to receive from datagram socket; rc = %d\n", rc);
            continue;
        }

        ui32SeqNum = *( (uint32*)buf );
        //printf ("udpServer:: received a packet with seq. number = %d and size %d from remote port %d\n", ui32SeqNum, rc, clientAddr.getPort());

        if (ui16ClientPort != clientAddr.getPort()) {
            if ( (ui16ClientPort != 0) && (lastSequenceNumber >= 0) ) {
                // The statistics can be printed only when the second cycle starts
                //printf ("UDP done timestamp %llu\n", ui64LastPacketTS);
                sprintf (logbuf, "UDP::\t\tLoss = %d%\tOutOfOrder = %d\tThroughput = %5.2f bytes/sec\n", 
                        (numPacketsLost * 100)/(lastSequenceNumber + 1),
                        outOfOrderPackets, 
                        (float) ui64TotalBytesReceived / (ui64LastPacketTS - ui64FirstPacketTS), 
                        ui64TotalBytesReceived
                       );

                printf ("%s", logbuf);
                fprintf (pLogFile, "%s", logbuf);
            }

            lastSequenceNumber = ui32SeqNum;
            numPacketsRecvd = 0;
            numPacketsLost = 0;
            outOfOrderPackets = 0;

            ui64FirstPacketTS = getTimeInMilliseconds();
            //printf ("UDP ui64FirstPacketTS %llu\n", ui64FirstPacketTS);
            ui64TotalBytesReceived = 0;

            ui16ClientPort = clientAddr.getPort();
        }
        
        numPacketsRecvd++;
        ui64TotalBytesReceived += rc;

        if (ui32SeqNum < lastSequenceNumber) {
            outOfOrderPackets++;
        }
        else if (ui32SeqNum != (lastSequenceNumber + 1)) {
            numPacketsLost += ui32SeqNum - lastSequenceNumber;
        }

        lastSequenceNumber = ui32SeqNum;
    }

    return 0;
}
Example #22
0
int	SockConnector::connect(SockStream &stream, InetAddr &addr, TimeValue &tv)
{	
	int rv = 0;

	// non-block socket
	stream.set_nonblocking();
	
	#ifdef _WIN32

	// connect
	rv = ::connect(stream.get_handle(), (const struct sockaddr *) addr.get_addr(), (socklen_t)addr.get_addr_size());
	if (rv != -1) {
		rv = 0;
	}
	else  {
		if (WSAGetLastError() == WSAEWOULDBLOCK) 
		{
			//printf("connect InProgress [%d]\n", sock);
			fd_set rset;
			fd_set wset;

			FD_ZERO(&rset);
			FD_ZERO(&wset);
			FD_SET(stream.get_handle(), &rset);			
			FD_SET(stream.get_handle(), &wset);			
			
			rv = ::select(0, &rset, &wset, NULL, (struct  timeval*)tv.timeval());
			if (rv == 0) {				
				perror("connect timeout");
				rv = -1;
			}
			else if (FD_ISSET(stream.get_handle(), &rset) || FD_ISSET(stream.get_handle(), &wset)) {
				int error = 0;
				socklen_t len = sizeof(error);
				if (getsockopt(stream.get_handle(), SOL_SOCKET, SO_ERROR, (char *)&error, &len) == 0) {
					// select error
					if (error == 0) {
						rv = 0;
					}
					else {
						closesocket(stream.get_handle());						
						perror("connect");		
						rv = -1;
					}	
				}
			}
			else {
				perror("connect");		
				rv = -1;

			}
		} 
		else {
			perror("connect");
			rv = -1;
		}
	}
	#endif

	// restore file status flags
	stream.set_blocking();
	
	return rv;
}