How to get Local IP Address

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lsgrandchamp

Hey,

How to get the local IP address?

Using IP.get_local_addresses() returns an array of every address used in the network, but how to know which of them is the actual local IP address? I’m using Windows and the right address is usually the index 9, but is it always the case?

Regards,
Lucas Sene

:bust_in_silhouette: Reply From: Gamemap

I had the same problem and used this: IP.resolve_hostname(str(OS.get_environment("COMPUTERNAME")),1)
(COMPUTERNAME is a windows enviroment variable)

I don’t know if this is a good way to get the IP address but it work on windows.

I hope that I could help,
Gamemap

Thanks, @Gamemap! It’s a much more elegant way to handle this issue than mine. I just need to check if this works on Linux or Mac too.

lsgrandchamp | 2021-05-27 20:17

Please write me as soon as you find out.

Gamemap | 2021-05-27 20:29

I have found out that the enviroment variables on Linux and Mac are diffrent to Windows.

So you should write this:

var ip_adress :String

if OS.has_feature("windows"):
	if OS.has_enviroment("COMPUTERNAME"):
		ip_adress =  IP.resolve_hostname(str(OS.get_environment("COMPUTERNAME")),1)
elif OS.has_feature("x11"):
	if OS.has_enviroment("HOSTNAME"):
		ip_adress =  IP.resolve_hostname(str(OS.get_environment("HOSTNAME")),1)
elif OS.has_feature("OSX"):
	if OS.has_enviroment("HOSTNAME"):
		ip_adress =  IP.resolve_hostname(str(OS.get_environment("HOSTNAME")),1)

I don’t know if HOSTNAME is correct for Mac.
Here is the Godot Documentation about OS.get_enviroment()

Gamemap | 2021-05-27 21:20

:bust_in_silhouette: Reply From: wyattb

Just do this to fetch the last ipv4 in the list

var ip
for address in IP.get_local_addresses():
	if (address.split('.').size() == 4):
		ip=address

Unfortunately, this didn’t work. For example, in my list of IP’s, I get 4 IPs that would meet this condition.

lsgrandchamp | 2021-05-29 20:35

I just added the 4 IPs to a list called local_ip_addresses, and when I needed to display the IP, I just got local_ip_addresses[1].

SF123 | 2022-05-05 17:55

This gets you the local IPv4 address in C# easily. Try to think of something for IPv6 if you really need it, but this is good enough as you develop

using System.Linq;

public string GetIP()
{
    return IP.GetLocalAddresses().First(IsLocalIP);
    bool IsLocalIP(string ip)
    {
        if (!ip.Contains('.'))
        {
            return false;
        }

        var segments = Array.ConvertAll(ip.Split('.'), int.Parse);
        
        // 10.0.0.0 to 10.255.255.255
        if (segments[0] == 10)
        {
            return true;
        }

        // 172.16.0.0 to 172.31.255.255
        if (segments[0] == 172 &&
            segments[1] >= 16 && segments[1] <= 31)
        {
            return true;
        }
        
        // 192.168.0.0 to 192.168.255.255 
        if (segments[0] == 192 && segments[1] == 168)
        {
            return true;
        }

        return false;
    }
}
1 Like

The question is from 2021, and it was imported so I don’t even think the original poster gets notified of this, but the above solution, while I’m sure it works, is in my opinion, overcomplicated.

private string GetLocalIpAddress()
{
	IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
	foreach (IPAddress ip in host.AddressList)
	{
		if (ip.AddressFamily == AddressFamily.InterNetwork)
		{
			return ip.ToString();
		}
	}

	// Handle failure or just return null.
	return null;
}

This function makes use of the System.Net and System.Net.Sockets namespaces.

Hmm, your solution returns 127.0.0.1 in my case, which isn’t really what was desired (we knew that loopback was the local ip address without writing any code).

As for necroing something from 2021, this is the only sensible post that comes up when searching for local ip implementation in godot, so I wrote something that works for keeping future records

For the most part, the loopback address being returned might be the result of a weird network configuration, but it’s still easier to check for the loopback address in one extra line, rather than try and reinvent a function that is already included.