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