|
7 | 7 | from datetime import datetime |
8 | 8 | from os import listdir |
9 | 9 | from pathlib import Path |
10 | | -from typing import Dict |
| 10 | +from typing import Dict, Optional |
11 | 11 |
|
12 | 12 | import aiohttp |
13 | 13 | from fastapi import FastAPI |
14 | 14 | from fastapi.responses import PlainTextResponse |
15 | 15 | from pip._internal.operations.freeze import freeze |
16 | 16 | from pydantic import BaseModel |
| 17 | +from starlette.responses import JSONResponse |
17 | 18 |
|
18 | 19 | from aleph.sdk.chains.remote import RemoteAccount |
19 | 20 | from aleph.sdk.client import AlephClient, AuthenticatedAlephClient |
@@ -91,13 +92,31 @@ async def read_aleph_messages(): |
91 | 92 | @app.get("/dns") |
92 | 93 | async def resolve_dns_hostname(): |
93 | 94 | """Check if DNS resolution is working.""" |
94 | | - info_inet, info_inet6 = socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP) |
95 | | - ipv4 = info_inet[4][0] |
96 | | - ipv6 = info_inet6[4][0] |
97 | | - return { |
98 | | - "ipv4": ipv4, |
99 | | - "ipv6": ipv6, |
100 | | - } |
| 95 | + hostname = "example.org" |
| 96 | + ipv4: Optional[str] = None |
| 97 | + ipv6: Optional[str] = None |
| 98 | + |
| 99 | + info = socket.getaddrinfo(hostname, 80, proto=socket.IPPROTO_TCP) |
| 100 | + if not info: |
| 101 | + logger.error("DNS resolution failed") |
| 102 | + |
| 103 | + # Iterate over the results to find the IPv4 and IPv6 addresses they may not all be present. |
| 104 | + # The function returns a list of 5-tuples with the following structure: |
| 105 | + # (family, type, proto, canonname, sockaddr) |
| 106 | + for info_tuple in info: |
| 107 | + if info_tuple[0] == socket.AF_INET: |
| 108 | + ipv4 = info_tuple[4][0] |
| 109 | + elif info_tuple[0] == socket.AF_INET6: |
| 110 | + ipv6 = info_tuple[4][0] |
| 111 | + |
| 112 | + if ipv4 and not ipv6: |
| 113 | + logger.warning(f"DNS resolution for {hostname} returned only an IPv4 address") |
| 114 | + elif ipv6 and not ipv4: |
| 115 | + logger.warning(f"DNS resolution for {hostname} returned only an IPv6 address") |
| 116 | + |
| 117 | + result = {"ipv4": ipv4, "ipv6": ipv6} |
| 118 | + status_code = 200 if len(info) > 1 else 503 |
| 119 | + return JSONResponse(content=result, status_code=status_code) |
101 | 120 |
|
102 | 121 |
|
103 | 122 | @app.get("/ip/address") |
|
0 commit comments