Skip to content

Instantly share code, notes, and snippets.

@joker1007
Created August 4, 2012 09:04
Show Gist options
  • Save joker1007/3256203 to your computer and use it in GitHub Desktop.
Save joker1007/3256203 to your computer and use it in GitHub Desktop.
class String
def is_ipv4?
self =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ && Regexp.last_match[1..4].map(&:to_i).all? {|i| i >= 0 && i <= 255} && Regexp.last_match[1..4].all? {|octet| octet == "0" || octet[0] != "0"}
end
def is_ipv6?
self =~ /([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+)/ && Regexp.last_match[1..8].all? {|hex_str| hex_str == "0" || hex_str[0] != "0"}
end
def is_mac?
mac_re1 = /([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+)/
mac_re2 = /([0-9a-fA-F]+)-([0-9a-fA-F]+)-([0-9a-fA-F]+)-([0-9a-fA-F]+)-([0-9a-fA-F]+)-([0-9a-fA-F]+)/
if self =~ mac_re1
Regexp.last_match[1..6].all? {|hex_str| hex_str.length == 2}
elsif self =~ mac_re2
Regexp.last_match[1..6].all? {|hex_str| hex_str.length == 2}
else
false
end
end
def to_bin
if self.is_ipv4?
"01"
elsif self.is_ipv6?
"10"
elsif self.is_mac?
"00"
else
"11"
end
end
end
class Decryptor
def bin2str(bin)
bin.to_i(2).chr
end
end
if defined?(RSpec) # RSpec読み込む時はテストコードの実行
describe "is_ipv4?" do
it do
"0.0.0.0".is_ipv4?.should be_true
end
it do
"256.0.0.0".is_ipv4?.should be_false
end
it do
"255.0.0.256".is_ipv4?.should be_false
end
end
describe "is_ipv6?" do
it do
"2001:db8:bd05:1d2:288a:1fc0:1:10ee".is_ipv6?.should be_true
end
it do
"2001:db8:bd05:1d2:288a:1fc0:0:10ee".is_ipv6?.should be_true
end
it do
"2001:db8:bd05:1d2:288a:1fc0:g:10ee".is_ipv6?.should be_false
end
it do
"2001:db8:bd05:1d2:288a:1fc0:A:10ee".is_ipv6?.should be_true
end
it do
"2001:db8:bd05:1d2:288a:1fc0:0001:10ee".is_ipv6?.should be_false
end
end
describe "is_mac?" do
it do
"00:11:22:33:44:55".is_mac?.should be_true
end
it do
"1A-B2-c3-d4-e5-f6".is_mac?.should be_true
end
it do
"2a:2b-40-54:10-01".is_mac?.should be_false
end
end
describe Decryptor do
describe "bin2str" do
it do
subject.bin2str("1000001").should == "A"
end
end
end
else # RSpec読み込まない時は標準入力を読んで暗号を解読する
puts STDIN.each_line.each_slice(4).inject("") {|output, lines_4|
decryptor = Decryptor.new
crypt_bin = lines_4.inject("") {|bin, line|
bin + line.chomp.to_bin
}
output + decryptor.bin2str(crypt_bin)
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment