+1 vote

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

Godot version 3.3
in Engine by (42 points)

2 Answers

+1 vote
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,
Gamemap

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

0 votes

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

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

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 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 webmaster@godotengine.org with your username.