I have a list of network segments, and would like my website to recognize what network segment users are connected to based on their IP address. This is so I can select their location automatically on my site vs them having to choose manually. Whats a good way or determining this?
So far I have the below.
To find the client IP address:
local_ip = UDPSocket.open {|s| s.connect('64.233.187.99', 1); s.addr.last }
My array of Network Segments:
network_segments = [
{"name"=>"Site 1", "starting_address"=>"192.168.168.1", "ending_address"=>"192.168.175.254"},
{"name"=>"Site 2", "starting_address"=>"192.168.184.1", "ending_address"=>"192.168.191.254"},
{"name"=>"Site 3", "starting_address"=>"192.168.176.1", "ending_address"=>"192.168.183.254"}
]
I've tried removing the periods from the IPs and looping through each network segment to see if local_ip is > starting_address and < the ending_address, but this doesn't seem accurate. It should only return one name, and it returns all of them.
Is there a better way to see if the local_ip is in between any of my network segment IPs?
ip = local_ip.delete('.').to_i
network_segments.each do |seg|
start_addr = seg['starting_address'].delete('.').to_i
end_addr = seg['ending_address'].delete('.').to_i
if ip > start_addr and ip < end_addr
puts seg['name']
end
end