network_utils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. Copyright (c) Contributors to the Open 3D Engine Project.
  3. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. SPDX-License-Identifier: Apache-2.0 OR MIT
  5. """
  6. import logging
  7. import psutil
  8. import socket
  9. logger = logging.getLogger(__name__)
  10. def check_for_listening_port(port):
  11. """
  12. Checks to see if the connection to the designated port was established.
  13. :param port: Port to listen to.
  14. :return: True if port is listening.
  15. """
  16. port_listening = False
  17. for conn in psutil.net_connections():
  18. if 'port={}'.format(port) in str(conn):
  19. port_listening = True
  20. return port_listening
  21. def check_for_remote_listening_port(port, ip_addr='127.0.0.1'):
  22. """
  23. Tries to connect to a port to see if port is listening.
  24. :param port: Port being tested.
  25. :param ip_addr: IP address of the host being connected to.
  26. :return: True if connection to the port is established.
  27. """
  28. port_listening = True
  29. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  30. try:
  31. sock.connect((ip_addr, port))
  32. except socket.error as err:
  33. # Socket error: Connection refused, error code 10061
  34. if err.errno == 10061:
  35. port_listening = False
  36. finally:
  37. sock.close()
  38. return port_listening
  39. def get_local_ip_address():
  40. """
  41. Finds the IP address for the primary ethernet adapter by opening a connection and grabbing its IP address.
  42. :return: The IP address for the adapter used to make the connection.
  43. """
  44. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  45. try:
  46. # Connecting to Google's public DNS so there is an open connection
  47. # and then getting the address used for that connection
  48. sock.connect(('8.8.8.8', 80))
  49. host_ip = sock.getsockname()[0]
  50. finally:
  51. sock.close()
  52. return host_ip