Skip to content

Loading…

Added open? method #18

Open
wants to merge 4 commits into from

3 participants

@thesp0nge

Hi there, I added an open?(addr, port) method to check if a socket can successfully opened to that pair.

@t3hk0d3

Test is environment dependent. This is bad :(

Use mocking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Dec 20, 2011
  1. @thesp0nge
Commits on Jan 9, 2012
  1. @thesp0nge

    Added socket timeout

    thesp0nge committed
Commits on Jan 10, 2012
  1. @thesp0nge

    Fixed typo

    thesp0nge committed
  2. @thesp0nge

    Added EPERM

    thesp0nge committed
This page is out of date. Refresh to see the latest.
Showing with 37 additions and 0 deletions.
  1. +32 −0 lib/ipaddress.rb
  2. +5 −0 test/ipaddress_test.rb
View
32 lib/ipaddress.rb
@@ -12,6 +12,8 @@
#
#++
+require 'socket'
+require 'timeout'
require 'ipaddress/ipv4'
require 'ipaddress/ipv6'
@@ -154,6 +156,36 @@ def self.deprecate(message = nil) # :nodoc:
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
warn("DEPRECATION WARNING: #{message}")
end
+
+
+ # Checks if the given string is an IP address,
+ # either IPv4 or IPv6 with the specified port opened
+ #
+ # Example:
+ #
+ # IPAddress::open?('120.32.32.3', 80)
+ # #=> true
+ #
+ # IPAddress::open?('120.32.32.3', -4)
+ # #=> false
+ #
+ def self.open?(addr, port)
+ begin
+ Timeout::timeout(2) do
+ begin
+ s = TCPSocket.new(addr, port)
+ s.close
+ return true
+ rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::EPERM
+ return false
+ end
+ end
+ rescue Timeout::Error
+ return false
+ end
+
+ end
+
end # module IPAddress
View
5 test/ipaddress_test.rb
@@ -50,6 +50,11 @@ def test_module_method_valid_ipv4_netmark?
assert_equal false, IPAddress::valid_ipv4_netmask?("10.0.0.1")
end
+ def test_module_medthod_is_open?
+ assert_equal true, IPAddress::open?('127.0.0.1', 3000)
+ assert_equal false, IPAddress::open?('127.0.0.1', 23)
+ end
+
end
Something went wrong with that request. Please try again.