1

I've got a Django app that (for obscure reasons) needs to know the IP address of the server it's running on to present it back to the client. I can be pretty sure that the server will have eth0 up and running, so really, I need the address of eth0.

What's the best way to get this? Ideally, this should be enumerated at uwsgi startup, and not necessarily every request. I thought about putting some code in settings.py, but think that might get run/enumerated on every request.

edit I should add that this is a debian linux server, running nginx and running a Django application within uwsgi.

growse
  • 3,554
  • 9
  • 43
  • 66
  • 1
    The IP address of your local `eth0` interface might not be the same one that your clients see and might be unreachable from their side (e.g. it might be on a private network) – lanzz Feb 06 '14 at 12:32
  • That's true generally, but in this specific case, the IP of eth0 is the IP that's relevant to the client. – growse Feb 06 '14 at 12:35
  • What exactly is the setup.... Is it nginx on top of uwsgi on top of django (for instance)? – Jon Clements Feb 06 '14 at 12:45
  • Yes, apologies, should have included in the question. Updated. – growse Feb 06 '14 at 12:49
  • @growse so are you after the IP of the nginx server? (eg... the "outermost" part of the stack?) Or, where the uwsgis (master/slaves) are, or where one where the django app servers from... ? – Jon Clements Feb 06 '14 at 12:56
  • I'm after the IP of the server that the `python` binary executing the Django application is running. – growse Feb 06 '14 at 13:02

1 Answers1

1

Here is the code that I use to get the public facing ip (on *nix systems):

# Hack to find machine NIC IP
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.4.4", 80))
MACHINE_IP = s.getsockname()[0]
s.close()
Sunny Nanda
  • 2,362
  • 1
  • 16
  • 10
  • Any ideas on the best way to integrate that into Django, so it's run on application startup and the result stored somewhere? – growse Feb 06 '14 at 12:45
  • You can put this code in `settings.py`. So it can be later used as `settings.MACHINE_IP` – Sunny Nanda Feb 06 '14 at 12:56
  • I'll give that a go, thanks. My concern is that if this is evaluated on every request it could have a performance impact. – growse Feb 06 '14 at 13:02
  • `settings.py` is not evaluated for each request, so you should be good to go. – Sunny Nanda Feb 06 '14 at 13:04