How can I get IP address of the visitor?

I want to know the country user/visitor accessing the public website. I think i can check the country if i get the ip address of the visitor using this database

Is anybody know how to get the ip of the website visitor without any external API (which takes some time)

Hi @AdishMuhammed:

You can get the origin ip address with frappe.local.request_ip on server side.
Guessing the country will need an (really) updated database, this is the reason to use external API service.

Hope this helps.

1 Like

Did you know any good free Api ? i have used previously. But that api detect a Saudi IP as UAE

I have tried frappe.local.request_ip as you suggested but got an error, my code is

ip = frappe.local.request_ip

# ip_split = list(map(int, ip_address.split('.')))

# country = frappe.db.sql('select country_code where "'+ip+'" between start_ip and end_ip;')

frappe.responce['message'] = str(ip)

and got error

Traceback (most recent call last):
  File "apps/frappe/frappe/", line 95, in application
    response = frappe.api.handle()
  File "apps/frappe/frappe/", line 55, in handle
    return frappe.handler.handle()
  File "apps/frappe/frappe/", line 48, in handle
    data = execute_cmd(cmd)
  File "apps/frappe/frappe/", line 72, in execute_cmd
    return run_server_script(server_script)
  File "apps/frappe/frappe/", line 90, in run_server_script
    response = frappe.get_doc("Server Script", server_script).execute_method()
  File "apps/frappe/frappe/core/doctype/server_script/", line 98, in execute_method
    _globals, _locals = safe_exec(self.script)
  File "apps/frappe/frappe/utils/", line 85, in safe_exec
  File "<serverscript>", line 7, in <module>
  File "apps/frappe/frappe/utils/", line 483, in _write
    raise SyntaxError(f"Not allowed to write to object {obj} of type {type(obj)}")
SyntaxError: Not allowed to write to object <function NamespaceDict.__getattr__.<locals>.default_function at 0x771bddd3a950> of type <class 'function'>

hope you help

Typo here … Try frappe.response['message'] = str(ip)

1 Like

does this work with API server script. it returns none

{ "message": "None" }

Looking through implementation, even if there is no X-Forwarded-For,REMOTE_ADDR headers the result should be unless the function not executed

def set_request_ip(self):
		if frappe.get_request_header("X-Forwarded-For"):
			frappe.local.request_ip = (frappe.get_request_header("X-Forwarded-For").split(",", 1)[0]).strip()

		elif frappe.get_request_header("REMOTE_ADDR"):
			frappe.local.request_ip = frappe.get_request_header("REMOTE_ADDR")

			frappe.local.request_ip = ""