0

Is it possible to get the IP of the default interface with Sanic?

Here is how I do it with Socket. The idea is to do the same thing with Sanic.

import socket
hostname = socket.gethostname()
IP_address = socket.gethostbyname(hostname)
print(IP_address) # 192.168.1.239
nico
  • 1,130
  • 2
  • 12
  • 26

1 Answers1

0

It depends upon what information you want and how the app is being served (reverse proxy, etc).

Check out these values:

Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52
  • 1
    If I execute `import sanic;print(sanic.request.Request.ip)`, python3 returns an object. Can you tell me how to get the IP in string format from this object? – nico Jul 10 '22 at 13:40
  • 1
    You are accessing a method of a class. You need the request instance, which is injected into every route handler. https://sanic.dev/en/guide/basics/handlers.html – Adam Hopkins Jul 10 '22 at 13:46
  • 1
    OK, I managed to get the IP in a route with your help. The problem is that I want to start the Sanic server with the correct IP (i.e., not “127.0.0.1”, but something like “192.168.1.239”) with `ip_address = get_ip(); app.run(host=ip_address, port=8000)`, i.e., before any request for a route. – nico Jul 10 '22 at 15:08
  • 1
    I think you are confusing the client ip address (the incoming request) and the server ip (something you define in app.run()). Whatever address you pass to app.run is what the server will bind to and what it will receive requests on. Maybe what you want is something like this: https://stackoverflow.com/q/166506 – Adam Hopkins Jul 10 '22 at 15:35