Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Contents
- [Contributing](#contributing)
- [Contact](#contact)
- [License](#license)

Installing
----------
```bash
Expand Down Expand Up @@ -279,8 +279,10 @@ Faker::Internet.domain_suffix #=> "info"

Faker::Internet.ip_v4_address #=> "24.29.18.175"

# Guaranteed not to be in 10.0.0.0/8, 127.0.0.0/8, 169.254.0.0/16,
# 172.16.0.0/12, or 192.168.0.0/16
# Private IP range according to RFC 1918 and 127.0.0.0/8 and 169.254.0.0/16.
Faker::Internet.private_ip_v4_address #=> "10.0.0.1"

# Guaranteed not to be in the ip range from the private_ip_v4_address method.
Faker::Internet.public_ip_v4_address #=> "24.29.18.175"

Faker::Internet.ip_v4_cidr #=> "24.29.18.175/21"
Expand Down
29 changes: 22 additions & 7 deletions lib/faker/internet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,36 @@ def ip_v4_address
ary.sample].join('.')
end

def private_ip_v4_address
is_private = private_net_checker
addr = nil
begin
addr = ip_v4_address
end while !is_private[addr]
addr
end

def public_ip_v4_address
private_nets = [
is_private = private_net_checker
addr = nil
begin
addr = ip_v4_address
end while is_private[addr]
addr
end

def private_nets_regex
[
/^10\./,
/^127\./,
/^169\.254\./,
/^172\.(16|17|18|19|2\d|30|31)\./,
/^192\.168\./
]
end

is_private = lambda {|addr| private_nets.any?{|net| net =~ addr}}
addr = nil
begin
addr = ip_v4_address
end while is_private[addr]
addr
def private_net_checker
lambda { |addr| private_nets_regex.any? { |net| net =~ addr } }
end

def ip_v4_cidr
Expand Down
15 changes: 15 additions & 0 deletions test/test_faker_internet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,21 @@ def test_ip_v4_address
end
end

def test_private_ip_v4_address
ten_dot = /^10\./
one_two_seven = /^127\./
one_six_nine = /^169\.254/
one_nine_two = /^192\.168\./
one_seven_two = /^172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\./

1000.times do
address = @tester.private_ip_v4_address
assert_match Regexp.new(
"(#{ten_dot})|(#{one_two_seven})|(#{one_six_nine})|(#{one_nine_two})|(#{one_seven_two})"
), address
end
end

def test_public_ip_v4_address
ten_dot = /^10\./
one_two_seven = /^127\./
Expand Down