14
« on: March 08, 2011, 03:20:14 pm »
It gave the same result.sf::IpAddress GetLocalAddress()
{
// The method here is to connect a UDP socket to anyone (here to localhost),
// and get the local socket address with the getsockname function.
// UDP connection will not send anything to the network, so this function won't cause any overhead.
sf::IpAddress localAddress;
// Create the socket
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET)
return localAddress;
// Connect the socket to localhost on any port
sockaddr_in address = CreateAddress(INADDR_LOOPBACK, 0);
if (connect(sock, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
{
closesocket(sock);
return localAddress;
}
char buffer[] = {0};
send(sock, buffer, 1, 0);
// Get the local address of the socket connection
int size = sizeof(address);
if (getsockname(sock, reinterpret_cast<sockaddr*>(&address), &size) == -1)
{
closesocket(sock);
return localAddress;
}
// Close the socket
closesocket(sock);
// Finally build the IP address
localAddress = sf::IpAddress(ntohl(address.sin_addr.s_addr));
return localAddress;
}