From cf355234c89548d38a4ccd3bb95991a7eef820fa Mon Sep 17 00:00:00 2001 From: gtitov Date: Tue, 28 Mar 2023 11:20:45 +0300 Subject: [PATCH] add host ip detection --- gui/index.html | 1 + gui/main.js | 4 ++++ main.py | 17 ++++++++++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/gui/index.html b/gui/index.html index 18aa87f..3c66c71 100644 --- a/gui/index.html +++ b/gui/index.html @@ -28,6 +28,7 @@ diff --git a/gui/main.js b/gui/main.js index 3ad8e99..43c6bfe 100644 --- a/gui/main.js +++ b/gui/main.js @@ -4,6 +4,10 @@ document.addEventListener("DOMContentLoaded", function () { var students_selector = document.getElementById("students-selector") var get_quiz_button = document.getElementById("get-quiz") + fetch("/hostip") + .then(r => r.json()) + .then(host_ip => document.getElementById("host-ip").innerText += ` ${host_ip}:8000`) + fetch("/students") .then(r => r.json()) .then(students => { diff --git a/main.py b/main.py index 886aa20..9bf4658 100644 --- a/main.py +++ b/main.py @@ -4,7 +4,8 @@ from fastapi.staticfiles import StaticFiles import json import random from pathlib import Path -from datetime import datetime +from datetime import datetime +import socket from settings import WAVE, END_TEST_PASSWORD, QUIZ_LENGTH, QUESTIONS_FILE, STUDENTS_FILE @@ -61,6 +62,20 @@ def check_answers(student_answers: dict): return checked_answers +@app.get("/hostip") +def show_host_ip(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.settimeout(0) + try: + # doesn't even have to be reachable + s.connect(('10.254.254.254', 1)) + ip = s.getsockname()[0] + except Exception: + ip = '127.0.0.1' + finally: + s.close() + return ip + @app.get("/students") def show_students(): return students