_ipaddress.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright 2021-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Test if a string is an IP Address"""
  15. import socket
  16. from bson.py3compat import _unicode
  17. try:
  18. from ipaddress import ip_address
  19. def is_ip_address(address):
  20. try:
  21. ip_address(_unicode(address))
  22. return True
  23. except (ValueError, UnicodeError):
  24. return False
  25. except ImportError:
  26. if hasattr(socket, 'inet_pton') and socket.has_ipv6:
  27. # Most *nix, Windows newer than XP
  28. def is_ip_address(address):
  29. try:
  30. # inet_pton rejects IPv4 literals with leading zeros
  31. # (e.g. 192.168.0.01), inet_aton does not, and we
  32. # can connect to them without issue. Use inet_aton.
  33. socket.inet_aton(address)
  34. return True
  35. except socket.error:
  36. try:
  37. socket.inet_pton(socket.AF_INET6, address)
  38. return True
  39. except socket.error:
  40. return False
  41. else:
  42. # No inet_pton
  43. def is_ip_address(address):
  44. try:
  45. socket.inet_aton(address)
  46. return True
  47. except socket.error:
  48. if ':' in address:
  49. # ':' is not a valid character for a hostname.
  50. return True
  51. return False