
Untitled
By: a guest on
May 5th, 2012 | syntax:
C++ | size: 1.49 KB | hits: 18 | expires: Never
//*****************************************************************************
//
bool NETWORK_StringToAddress( const char *s, NETADDRESS_s *a )
{
struct addrinfo hints;
struct addrinfo *res;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_DGRAM; // UDP stream socket
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
std::string host;
std::string port;
std::string address(s);
int leftBracketIndex;
int rightBracketIndex;
if ((leftBracketIndex = address.find_last_of('[')) != -1 && (rightBracketIndex = address.find_last_of(']')) != -1)
{
host = address.substr(leftBracketIndex + 1, rightBracketIndex - 1);
int portBeginIndex;
if (address[portBeginIndex = rightBracketIndex+1] == ':')
{
port = address.substr(portBeginIndex, address.length() - 1);
}
}
else
{
int coloncount = 0;
for (int i = 0; i < address.length(); i++)
if (address[i] == ':')
coloncount++;
if (coloncount != 1)
host = address;
else
{
int portBeginIndex = address.find_last_of(':') + 1;
port = address.substr(portBeginIndex, address.length() - 1);
}
}
if (getaddrinfo(host.c_str(), port.c_str(), &hints, &res) != 0 )
{
Printf("Warning: Could not resolve address.\n");
return false;
}
// [WS] Let's get the network address.
NETWORK_AddressInfoToNetAddress( res, a );
a->usPort = htons(atoi(port.c_str()));
return true;
}