Пример #1
0
   bool
   LocalIPAddresses::IsWithinLoopbackRange(const IPAddress &address)
   {
      if (address.GetType() == IPAddress::IPV4)
      {
         unsigned __int64 longAddress = address.GetAddress1();
      
         // 127.0.0.1 - 127.255.255.255
         if (longAddress >= 2130706433 && longAddress <= 2147483647)
            return true;
         else
            return false;
      }
      else if (address.GetType() == IPAddress::IPV6)
      {
         if (address.GetAddress1() == 0 && address.GetAddress2() == 1)
            return true;
         else
            return false;
      }

      return true;
      

      /*

         */
   }
Пример #2
0
   bool
   TCPConnection::Connect(const AnsiString &remote_ip_address, long remotePort, const IPAddress &localAddress)
   {
#if _DEBUG
      if (!StringParser::IsValidIPAddress(remote_ip_address))
      {
         ErrorManager::Instance()->ReportError(ErrorManager::High, 5506, "TCPConnection::Connect", 
            Formatter::Format("Attempting to connect to {0} - Not a valid IP address.", remote_ip_address));
      }
#endif

      remote_port_ = remotePort;
      remote_ip_address_ = remote_ip_address;
      is_client_ = true;

      LOG_TCPIP(Formatter::Format("Connecting to {0}:{1}...", remote_ip_address_, remotePort));

      if (!localAddress.IsAny())
      {
         boost::system::error_code error_code;

         if (localAddress.GetType() == IPAddress::IPV4)
            socket_.open(boost::asio::ip::tcp::v4(), error_code);
         else if (localAddress.GetType() == IPAddress::IPV6)
            socket_.open(boost::asio::ip::tcp::v6(), error_code);

         if (error_code)
         {
            String errorMessage = Formatter::Format("Failed to open local socket on IP address {0}", localAddress.ToString());
            OnCouldNotConnect(errorMessage);
            ReportError(ErrorManager::Medium, 5520, "TCPConnection::Connect", errorMessage, error_code);
            return false;
         }

         socket_.bind(boost::asio::ip::tcp::endpoint(localAddress.GetAddress(), 0), error_code);


         if (error_code)
         {
            String errorMessage = Formatter::Format("Failed to bind to IP address {0}.", localAddress.ToString());
            ReportError(ErrorManager::Medium, 4330, "TCPConnection::Connect", errorMessage, error_code);
            OnCouldNotConnect(errorMessage);

            boost::system::error_code ignored_error_code;
            socket_.close(ignored_error_code);
            return false;
         }
      }

      // Start an asynchronous resolve to translate the server and service names
      // into a list of endpoints.
      StartAsyncConnect_(remote_ip_address, remotePort);
      return true;
   }
Пример #3
0
/** @details The broadcast address can only be calculated on a IPv4 network.  While it is
 *  technically possible to calculate an IPv6 broadcast address, the IPv6 protocol has dropped
 *  support for broadcasting.  Since broadcasting is not supported in IPv6, this method will result
 *  in an exception given an IPv6 address.
 *  @param ip An IP address on the network.
 *  @param netmask The netmask defining the network range.
 *  @returns The broadcast address.
 */
_CGUL_EXPORT CGUL::Network::IPAddress CGUL::Network::IPAddress::CalculateBroadcast(const IPAddress& ip, const IPAddress& netmask)
{
    if (ip.GetType() == IPAddressType::IPV6 || netmask.GetType() == IPAddressType::IPV6)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_INVALID);
    }
    if (!ip.IsValid() || ip.GetType() != netmask.GetType())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_MISMATCH);
    }

    return IPAddress(ip.ToUInt32() | (~netmask.ToUInt32()));
}
Пример #4
0
   bool 
   DNSResolver::GetPTRRecords(const String &sIP, std::vector<String> &vecFoundNames)
   {
      IPAddress address;
      if (!address.TryParse(AnsiString(sIP), true))
         return false;

      if (address.GetType() == IPAddress::IPV4)
      {
         std::vector<String> vecItems = StringParser::SplitString(sIP, ".");
         reverse(vecItems.begin(), vecItems.end());
         String result = StringParser::JoinVector(vecItems, ".");
         return Resolve_(result + ".in-addr.arpa", vecFoundNames, DNS_TYPE_PTR, 0);
      }
      else
      {
         AnsiString long_ipv6 = address.ToLongString();
         long_ipv6.MakeReverse();
         long_ipv6.Remove(':');

         for (int i = long_ipv6.GetLength() - 1; i > 0; i--)
         {
            long_ipv6.insert(i, 1, '.');
         }

         return Resolve_(long_ipv6 + ".ip6.arpa", vecFoundNames, DNS_TYPE_PTR, 0);
      }


   }
   shared_ptr<SecurityRange>
   PersistentSecurityRange::ReadMatchingIP(const IPAddress &ipaddress)
   {
      shared_ptr<SecurityRange> empty;

      IPAddressSQLHelper helper;
      String sSQL;

      if (ipaddress.GetType() == IPAddress::IPV4)
      {
         shared_ptr<SecurityRange> pSR = shared_ptr<SecurityRange>(new SecurityRange());

         sSQL.Format(_T("select * from hm_securityranges where %s >= rangelowerip1 and %s <= rangeupperip1 and rangelowerip2 IS NULL and rangeupperip2 IS NULL order by rangepriorityid desc"), 
            String(helper.GetAddress1String(ipaddress)), String(helper.GetAddress1String(ipaddress)));

         if (!ReadObject(pSR, SQLCommand(sSQL)))
            return empty;

         return pSR;
      }
      else
      {
         // Read all IPv6 items.
         shared_ptr<SecurityRange> bestMatch;

         SQLCommand command(_T("select * from hm_securityranges where rangelowerip2 is not null order by rangepriorityid desc"));
         
         shared_ptr<DALRecordset> recordset = Application::Instance()->GetDBManager()->OpenRecordset(command);
         if (!recordset)
            return empty;

         while (!recordset->IsEOF())
         {
            shared_ptr<SecurityRange> securityRange = shared_ptr<SecurityRange>(new SecurityRange());

            if (ReadObject(securityRange, recordset) == false)
               return empty;

            if (ipaddress.WithinRange(securityRange->GetLowerIP(), securityRange->GetUpperIP()))
            {
               // This IP range matches the client. Does it have higher prio than the currently
               // matching?

               if (!bestMatch || securityRange->GetPriority() > bestMatch->GetPriority())
                  bestMatch = securityRange;
            }

            recordset->MoveNext();
         }

         return bestMatch;
      }


      
   }
Пример #6
0
   AnsiString 
   IPAddressSQLHelper::GetAddress2Equals(const IPAddress &address) const
   {
      if (address.GetType() == IPAddress::IPV4)
         return "IS NULL";

      String s;
      s.Format(_T("= %I64d"), address.GetAddress2());
      return s;
   }
Пример #7
0
/** @details A network address defines the "bottom-most" address for a given network.
 *  @param ip An IP address on the network.
 *  @param netmask The netmask defining the network range.
 *  @returns The network address.
 */
_CGUL_EXPORT CGUL::Network::IPAddress CGUL::Network::IPAddress::CalculateNetwork(const IPAddress& ip, const IPAddress& netmask)
{
    if (!ip.IsValid() || ip.GetType() != netmask.GetType())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_MISMATCH);
    }

    if (ip.GetType() == IPAddressType::IPV4)
    {
        return IPAddress(ip.ToUInt32() & netmask.ToUInt32());
    }
    else
    {
        UInt64 network[2];
        network[0] = ip.address[0] & netmask.address[0];
        network[1] = ip.address[1] & netmask.address[1];
        return IPAddress(network);
    }
}
Пример #8
0
   void 
   IPAddressSQLHelper::AppendStatement(SQLStatement &statement, const IPAddress &address, const AnsiString &address1Column, const AnsiString &address2Column) const
   {
      statement.AddColumnInt64(address1Column, address.GetAddress1());
      
      if (address.GetType() == IPAddress::IPV6)
         statement.AddColumnInt64(address2Column, address.GetAddress2());
      else
         statement.AddColumnNULL(address2Column);

   }
Пример #9
0
/** @brief Connects to a server on a given ip and port.
 *  @param ip The IP address to connect to.
 *  @param port The port number.
 */
void Jatta::Network::SocketTCP::Connect(const IPAddress& ip, unsigned short port)
{
    // Check that the IP is valid
    if (!ip.IsValid())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::ADDRESS_INVALID);
    }

    // Create a hints variable used to determine the connection configuration.
    struct addrinfo hints;
    memset(&hints, 0, sizeof(addrinfo));

    // Check if the IP is an IPv4 or IPv6.
    if (ip.GetType() == IPAddressType::IPV4)
    {
        // Use IPv4.
        hints.ai_family = AF_INET;
    }
    else
    {
        // Use IPv6.
        hints.ai_family = AF_INET6;
    }

    // We're setting up a TCP/IP connection, which is a STREAM socket.
    hints.ai_socktype = SOCK_STREAM;

    // Convert the port into a string.
    char portString[6];
#   ifdef MSVC
    sprintf_s(portString, "%d", port);
#   else
    sprintf(portString, "%d", port);
#   endif

    // Get the address info using the hints.
    addrinfo* result;
    if (getaddrinfo(ip.ToString().GetCString(), portString, &hints, &result) != 0)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::NO_NETWORK_INTERFACE);
    }

    // Create the socket.  Because our hints are so strict, we don't have to worry about looping
    // through the linked list.  We should be able to trust that the first result is what we want.
    sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (sock == INVALID_SOCKET)
    {
        freeaddrinfo(result);
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_CREATE_SOCKET);
    }

    // Make the connection.
    if (::connect(sock, result->ai_addr, result->ai_addrlen) == SOCKET_ERROR)
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_CONNECT_CALL);
    }

    // Make a non-blocking socket.
    if (!MakeNonBlocking())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_NONBLOCKING);
    }

    // Turn off the Nagle Algorithm to increase speed.
    if (!MakeNoDelay())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_NO_DELAY);
    }

    // Free up the address info linked list.
    freeaddrinfo(result);
}