Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Websocket cannot trace client's IP? #11648

Answered by YuriiMotov
Zhaoxun asked this question in Questions
Discussion options

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

################utils.py##########################################
import logging
logger = logging.getLogger("test")
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
sfmt = logging.Formatter(
        "%(asctime)s - %(levelname)s [%(filename)s:%(lineno)d] - %(message)s",
)
sh.setFormatter(sfmt)
logger.addHandler(sh)

log = logger

############main.py#############

from fastapi import FastAPI, Request
from fastapi import WebSocket, WebSocketDisconnect
from utils import log
from users import ws

WS = FastAPI()

@WS.websocket('/')
async def host_client(request:Request, session: WebSocket):
    log.warning('from', request.client.host)
......

Description

I cannot retrieve client's IP like in the http connection/request, just like in this page

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.111.0

Pydantic Version

2.7.1

Python Version

3.9.16

Additional Context

No response

You must be logged in to vote

It can be done this way:

from fastapi import FastAPI
from fastapi import WebSocket

WS = FastAPI()

@WS.websocket('/')
async def host_client(websocket: WebSocket):
    print('from', websocket.client.host)

Replies: 1 comment

Comment options

It can be done this way:

from fastapi import FastAPI
from fastapi import WebSocket

WS = FastAPI()

@WS.websocket('/')
async def host_client(websocket: WebSocket):
    print('from', websocket.client.host)
You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.