Reputation: 131
I have a database table that contains MAC addresses. Currently I am doing this:
<% @devices.each do |device| %>
<tr>
<td><%= device.mac_address %></td>
</tr>
<% end %>
And I have two variables called data
that contains a string:
Host is up (0.00s latency). MAC Address: 00:95:7F:A9:A3:81 (Unknown) Nmap scan report for 192.168.1.3 Host is up (0.0020s latency). MAC Address: 00:66:19:38:2E:7E (Unknown) Nmap scan report for 192.168.1.4
Host is up (0.0030s latency). MAC Address: 00:66:19:38:2F:00 (Unknown)
Nmap scan report for 192.168.1.5
As I am looping over the MAC addresses, how can I parse data
to find the IP following the Mac address? If the current MAC address in the loop is 00:95:7F:A9:A3:81
I need to output 192.168.1.3
as the IP.
Upvotes: 0
Views: 487
Reputation: 160631
Meditate on this:
MAC_ADDRESSES = %w[
00:95:7F:A9:A3:81
00:66:19:38:2E:7E
00:66:19:38:2F:00
]
IP_REGEX = /(?:\d{1,3}\.){3}\d{1,3}/
RESULT = 'Host is up (0.00s latency). MAC Address: 00:95:7F:A9:A3:81 (Unknown) Nmap scan report for 192.168.1.3 Host is up (0.0020s latency). MAC Address: 00:66:19:38:2E:7E (Unknown) Nmap scan report for 192.168.1.4 Host is up (0.0030s latency). MAC Address: 00:66:19:38:2F:00 (Unknown) Nmap scan report for 192.168.1.5'
pairs = MAC_ADDRESSES.map { |mac|
[mac, RESULT[/#{mac}.+?(#{IP_REGEX})/, 1]]
}.to_h
pairs
# => {"00:95:7F:A9:A3:81"=>"192.168.1.3",
# "00:66:19:38:2E:7E"=>"192.168.1.4",
# "00:66:19:38:2F:00"=>"192.168.1.5"}
pairs['00:66:19:38:2E:7E'] # => "192.168.1.4"
Upvotes: 1
Reputation: 1759
I'd use Regex here:
macs.each do |mac|
if @result =~ /#{mac.mac_address}.*?for (\d+\.\d+\.\d+\.\d+)/
ip = $1
puts "#{mac} - #{ip}"
end
end
Upvotes: 0