ip command is not installed by default in MacOS(Sonoma).
Probably something like below can do the job(in my machine at least):
ifconfig en0 | grep -E 'inet\b' | cut -f 2 -d ' '
Linux also has ifconfig installed but it's deprecated now.
There is another cross-platform solution like:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
But it needs internet connection.