|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +# pyre-strict |
| 8 | +import logging |
| 9 | +import socket |
| 10 | +from typing import Optional |
| 11 | + |
| 12 | +logger: logging.Logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +def get_ip_addr(hostname: str) -> str: |
| 16 | + """Resolves and returns the ip address of the given hostname. |
| 17 | +
|
| 18 | + This function will return an ipv6 address if one that can bind |
| 19 | + `SOCK_STREAM` (TCP) socket is found. Otherwise it will fall-back |
| 20 | + to resolving an ipv4 `SOCK_STREAM` address. |
| 21 | +
|
| 22 | + Raises a `RuntimeError` if neither ipv6 or ipv4 ip can be resolved from hostname. |
| 23 | + """ |
| 24 | + |
| 25 | + def get_sockaddr(family: socket.AddressFamily) -> Optional[str]: |
| 26 | + try: |
| 27 | + addrs = socket.getaddrinfo( |
| 28 | + hostname, port=None, family=family, type=socket.SOCK_STREAM |
| 29 | + ) # tcp |
| 30 | + if addrs: |
| 31 | + # socket.getaddrinfo return a list of addr 5-tuple addr infos |
| 32 | + _, _, _, _, sockaddr = addrs[0] # use the first address |
| 33 | + |
| 34 | + # sockaddr is a tuple (ipv4) or a 4-tuple (ipv6) where the first element is the ip addr |
| 35 | + ipaddr = str(sockaddr[0]) |
| 36 | + |
| 37 | + logger.info( |
| 38 | + "Resolved %s address: `%s` for host: `%s`", |
| 39 | + family.name, |
| 40 | + ipaddr, |
| 41 | + hostname, |
| 42 | + ) |
| 43 | + return str(ipaddr) |
| 44 | + else: |
| 45 | + return None |
| 46 | + except socket.gaierror as e: |
| 47 | + logger.info( |
| 48 | + "No %s address that can bind TCP sockets for host: %s. %s", |
| 49 | + family.name, |
| 50 | + hostname, |
| 51 | + e, |
| 52 | + ) |
| 53 | + return None |
| 54 | + |
| 55 | + ipaddr = get_sockaddr(socket.AF_INET6) or get_sockaddr(socket.AF_INET) |
| 56 | + if not ipaddr: |
| 57 | + raise RuntimeError( |
| 58 | + f"Unable to resolve `{hostname}` to ipv6 or ipv4 address that can bind TCP socket." |
| 59 | + " Check the network configuration on the host." |
| 60 | + ) |
| 61 | + return ipaddr |
0 commit comments