/lib/mongo/address/ipv6.rb

https://github.com/brblck/mongo-ruby-driver · Ruby · 90 lines · 28 code · 9 blank · 53 comment · 1 complexity · d7379fb36f11dd8459f32cd21bd4cdcf MD5 · raw file

  1. # Copyright (C) 2014-2016 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. module Mongo
  15. class Address
  16. # Sets up resolution with IPv6 support if the address is an ip
  17. # address.
  18. #
  19. # @since 2.0.0
  20. class IPv6
  21. # @return [ String ] host The host.
  22. attr_reader :host
  23. # @return [ String ] host_name The original host name.
  24. attr_reader :host_name
  25. # @return [ Integer ] port The port.
  26. attr_reader :port
  27. # The regular expression to use to match an IPv6 ip address.
  28. #
  29. # @since 2.0.0
  30. MATCH = Regexp.new('::').freeze
  31. # Parse an IPv6 address into its host and port.
  32. #
  33. # @example Parse the address.
  34. # IPv4.parse("[::1]:28011")
  35. #
  36. # @param [ String ] address The address to parse.
  37. #
  38. # @return [ Array<String, Integer> ] The host and port pair.
  39. #
  40. # @since 2.0.0
  41. def self.parse(address)
  42. parts = address.match(/\[(.+)\]:?(.+)?/)
  43. host = parts[1]
  44. port = (parts[2] || 27017).to_i
  45. [ host, port ]
  46. end
  47. # Initialize the IPv6 resolver.
  48. #
  49. # @example Initialize the resolver.
  50. # IPv6.new("::1", 28011, 'localhost')
  51. #
  52. # @param [ String ] host The host.
  53. # @param [ Integer ] port The port.
  54. #
  55. # @since 2.0.0
  56. def initialize(host, port, host_name=nil)
  57. @host = host
  58. @port = port
  59. @host_name = host_name
  60. end
  61. # Get a socket for the provided address type, given the options.
  62. #
  63. # @example Get an IPv6 socket.
  64. # ipv4.socket(5, :ssl => true)
  65. #
  66. # @param [ Float ] timeout The socket timeout.
  67. # @param [ Hash ] ssl_options SSL options.
  68. #
  69. # @return [ Pool::Socket::SSL, Pool::Socket::TCP ] The socket.
  70. #
  71. # @since 2.0.0
  72. def socket(timeout, ssl_options = {})
  73. unless ssl_options.empty?
  74. Socket::SSL.new(host, port, host_name, timeout, Socket::PF_INET6, ssl_options)
  75. else
  76. Socket::TCP.new(host, port, timeout, Socket::PF_INET6)
  77. end
  78. end
  79. end
  80. end
  81. end