diff --git a/doc/changelog.d/4095.miscellaneous.md b/doc/changelog.d/4095.miscellaneous.md new file mode 100644 index 0000000000..37b1972b1b --- /dev/null +++ b/doc/changelog.d/4095.miscellaneous.md @@ -0,0 +1 @@ +Fix: (migrated pr 4094): fix socket.gethostbyaddr(ip) error when no reverse dns available. \ No newline at end of file diff --git a/src/ansys/mapdl/core/mapdl_grpc.py b/src/ansys/mapdl/core/mapdl_grpc.py index be3cc7e458..76eaf53ad9 100644 --- a/src/ansys/mapdl/core/mapdl_grpc.py +++ b/src/ansys/mapdl/core/mapdl_grpc.py @@ -31,7 +31,6 @@ import pathlib import re import shutil -import socket # Subprocess is needed to start the backend. But # the input is controlled by the library. Excluding bandit check. @@ -87,8 +86,8 @@ from ansys.mapdl.core.mapdl_types import KwargDict, MapdlFloat, MapdlInt from ansys.mapdl.core.misc import ( check_valid_ip, + get_ip_hostname, last_created, - only_numbers_and_dots, random_string, run_as, supress_logging, @@ -373,18 +372,9 @@ def __init__( if ip is None: ip = start_parm.pop("ip", None) or "127.0.0.1" - # setting hostname - if not only_numbers_and_dots(ip): - # it is a hostname - self._hostname = ip - ip = socket.gethostbyname(ip) - else: - # it is an IP - self._hostname = ( - "localhost" - if ip in ["127.0.0.1", "127.0.1.1", "localhost"] - else socket.gethostbyaddr(ip)[0] - ) + # setting hostname and ip + ip, hostname = get_ip_hostname(ip) + self._hostname = hostname check_valid_ip(ip) self._ip: str = ip diff --git a/src/ansys/mapdl/core/misc.py b/src/ansys/mapdl/core/misc.py index d81f4b7202..c7ae2623cc 100644 --- a/src/ansys/mapdl/core/misc.py +++ b/src/ansys/mapdl/core/misc.py @@ -666,3 +666,23 @@ def deco(f): return f return deco + + +def get_ip_hostname(ip: str) -> Tuple[str, str]: + """Get ip and hostname""" + if not only_numbers_and_dots(ip): + # it is a hostname + hostname = ip + ip = socket.gethostbyname(ip) + else: + # it is an IP + if ip in ["127.0.0.1", "127.0.1.1", "localhost"]: + hostname = "localhost" + else: + try: + hostname = socket.gethostbyaddr(ip)[0] + except OSError: + # If the IP address does not resolve to a hostname, use the IP + hostname = ip + + return ip, hostname