I wrote a simple program which reads IpTables log results , remove 90% of the output , and what is left is:
192.168.1.1 152
192.168.1.1 17485
192.168.1.1 5592
Where, the first column contains source IP , the second one destination Port. Those values are stored in a string. I would like to transfer the values from that string to a Hashtable, but I don't have any idea how.
Hashtable<String, String> IpDpt = new Hashtable<String, String>();
hmIpDpt.put(IP1,DPT1);
hmIpDpt.put(IP1,DPT2);
hmIpDpt.put(IP1,DPT3);
hmIpDpt.put(IP2,DPT4);
if you transferred to hashtable
then you will not have all the logs available because hashtable
does not allows duplicate values and in your log there may be chances of duplicate values . so hashtable
overrides values.
Try this program.
String info = "192.168.1.1 152";
Hashtable<String, List<String>> IpDpt = new Hashtable<String, List<String>>();
String[] values = info.split( " " );
String key = values[0];
String value = values[1];
if ( IpDpt.containsKey( key ) )
IpDpt.get( key ).add( value );
else
IpDpt.put( key, new ArrayList<String>( Arrays.asList( value ) ) );
To check whether the key has at least 100 values
if(IpDpt.containsKey( key ) && IpDpt.get( key ).size() >=100)
{
// business logic here
}
For every line you read, split the string on space like that:
String line = "192.168.1.1 152";
String[] parts = line.split(" ");
you_map.put(parts[0], parts[1]);
That should do it.
A Map cannot hold multiple values per key. So you should either use a third party library that offers something like a MultiMap
, or use a Set
to hold the values:
Map<String, Set<String>> ipToPortMap = new HashMap<>();
public void addEntry(String ip, String port) {
Set<String> ports = ipToPortMap.get(ip);
if (ports == null) {
ports = new HashSet<>();
ipToPortMap.put(ip, ports);
}
ports.add(port);
}
Now just iterate over your input (maybe using a Scanner
) and call addEntry
.
Use Guava Multimap
to allow duplicate key.
Multimap<String,String> multimap=ArrayListMultimap.create();
//put your ips and port.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.