+1 vote


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?

Lucas Sene

Godot version 3.3
in Engine by (49 points)

2 Answers

+2 votes
Best answer

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,

by (224 points)
selected by

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.

Please write me as soon as you find out.

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()

+1 vote

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):
by (809 points)

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.