Skip to content

Commit

Permalink
Fix IP address when app is behind Application LB
Browse files Browse the repository at this point in the history
  • Loading branch information
pnedkov committed Dec 29, 2023
1 parent 0c46df0 commit a574aa0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
2 changes: 1 addition & 1 deletion ipget/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.0.2
0.0.3
14 changes: 10 additions & 4 deletions ipget/ipget.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,22 @@ def get_country(ip):
return "N/A"


def get_client_ip():
xff_ip = request.headers.get("X-Forwarded-For")

return xff_ip if xff_ip else request.headers.get("X-Real-IP", request.remote_addr)


@app.route("/")
def home():
client_ip = request.headers.get("X-Real-IP", request.remote_addr)
client_ip = get_client_ip()
user_agent = request.headers.get("User-Agent", "").lower()

if "mozilla" in user_agent or "chrome" in user_agent or "safari" in user_agent:
client_info = {
"ip": client_ip,
"remote_hostname": urlparse("//" + str(request.headers.get("Host"))).netloc,
"x_forwarded_for": request.headers.get("X-Forwarded-For"),
"xff": request.headers.get("X-Forwarded-For"),
"country": get_country(client_ip),
"user_agent": request.user_agent.string,
"headers": format_headers(request.headers),
Expand All @@ -63,7 +69,7 @@ def home():

@app.route("/ip")
def return_ip():
return f"{request.headers.get('X-Real-IP', request.remote_addr)}\n"
return f"{get_client_ip()}\n"


@app.route("/host")
Expand All @@ -78,7 +84,7 @@ def return_xff():

@app.route("/country")
def return_country():
return f"{get_country(request.headers.get('X-Real-IP', request.remote_addr))}\n"
return f"{get_country(get_client_ip())}\n"


@app.route("/ua")
Expand Down
2 changes: 1 addition & 1 deletion ipget/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<tr>
<td>curl {{ client_info.remote_hostname }}/xff</td>
<td>X-Forwarded-For</td>
<td>{{ client_info.x_forwarded_for }}</td>
<td>{{ client_info.xff }}</td>
</tr>
{% if ip_api %}
<tr>
Expand Down

0 comments on commit a574aa0

Please sign in to comment.