Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: C++  |  size: 1.49 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //*****************************************************************************
  2. //
  3. bool NETWORK_StringToAddress( const char *s, NETADDRESS_s *a )
  4. {
  5.         struct addrinfo hints;
  6.         struct addrinfo *res;
  7.  
  8.         memset(&hints, 0, sizeof hints);        // make sure the struct is empty
  9.         hints.ai_family = AF_UNSPEC;            // don't care IPv4 or IPv6
  10.         hints.ai_socktype = SOCK_DGRAM;         // UDP stream socket
  11.         hints.ai_flags = AI_PASSIVE;            // fill in my IP for me
  12.  
  13.         std::string host;
  14.         std::string port;
  15.         std::string address(s);
  16.  
  17.         int leftBracketIndex;
  18.         int rightBracketIndex;
  19.         if ((leftBracketIndex = address.find_last_of('[')) != -1 && (rightBracketIndex = address.find_last_of(']')) != -1)
  20.         {
  21.                 host = address.substr(leftBracketIndex + 1, rightBracketIndex - 1);
  22.  
  23.                 int portBeginIndex;
  24.                 if (address[portBeginIndex = rightBracketIndex+1] == ':')
  25.                 {
  26.                         port = address.substr(portBeginIndex, address.length() - 1);
  27.                 }
  28.         }
  29.         else
  30.         {
  31.                 int coloncount = 0;
  32.                 for (int i = 0; i < address.length(); i++)
  33.                         if (address[i] == ':')
  34.                                 coloncount++;
  35.  
  36.                 if (coloncount != 1)
  37.                         host = address;
  38.                 else
  39.                 {
  40.                         int portBeginIndex = address.find_last_of(':') + 1;
  41.                         port = address.substr(portBeginIndex, address.length() - 1);
  42.                 }
  43.         }
  44.  
  45.         if (getaddrinfo(host.c_str(), port.c_str(), &hints, &res) != 0 )
  46.         {
  47.                 Printf("Warning: Could not resolve address.\n");
  48.                 return false;
  49.         }
  50.  
  51.         // [WS] Let's get the network address.
  52.         NETWORK_AddressInfoToNetAddress( res, a );
  53.         a->usPort = htons(atoi(port.c_str()));
  54.         return true;
  55. }