1 package edu.uci.iotproject.util;
3 import edu.uci.iotproject.DnsMap;
4 import edu.uci.iotproject.analysis.PcapPacketPair;
7 import java.util.stream.Collectors;
10 * Utility methods for generating (output) strings.
12 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
13 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
15 public class PrintUtils {
17 private PrintUtils() { /* private constructor to prevent instantiation */ }
21 * Converts a {@code PcapPacketPair} into a CSV string containing the packet lengths of the two packets in the pair.
23 * For example, the resulting string will be "123, 456" if the first packet of the pair has a length of 123 and the
24 * second packet of the pair has a length of 456.
26 * @return a CSV string containing the packet lengths of the two packets of the given {@code PcapPacketPair}.
28 public static String toCsv(PcapPacketPair packetPair) {
29 return String.format("%d, %d", packetPair.getFirst().getOriginalLength(),
30 packetPair.getSecond().getOriginalLength());
34 * Converts a {@code PcapPacketPair} into a CSV string containing the packet lengths of the two packets in the pair
35 * followed by the source of each packet. The source will be a (set of) hostname(s) if the source IP can be resolved
36 * to a (set of) hostname(s) using the provided {@link DnsMap}.
38 * For example, the resulting string will be "123, 456, 192.168.1.42, domain.com" if the first packet of the pair
39 * has a length of 123, the second packet of the pair has a length of 456, the first packet of the pair the pair has
40 * a source IP of '192.168.1.42' that cannot be resolved to a hostname, and the second packet of the pair has an IP
41 * that resolves to 'domain.com'.
43 * @return a CSV string containing the packet lengths of the two packets of the given {@code PcapPacketPair} as well
44 * as their respective sources.
46 public static String toCsv(PcapPacketPair packetPair, DnsMap ipHostnameMappings) {
47 // First obtain source IPs
48 String firstSrc = PcapPacketUtils.getSourceIp(packetPair.getFirst());
49 String secondSrc = PcapPacketUtils.getSourceIp(packetPair.getSecond());
51 // If possible, map source IPs to hostnames.
52 Set<String> firstHostnames = ipHostnameMappings.getHostnamesForIp(firstSrc);
53 Set<String> secondHostnames = ipHostnameMappings.getHostnamesForIp(secondSrc);
54 final String delimiter = " ";
55 if (firstHostnames != null) {
56 // If one IP maps to multiple hostnames, we concatenate the hostnames (separated by a delimiter)
57 firstSrc = firstHostnames.stream().collect(Collectors.joining(delimiter));
59 if (secondHostnames != null) {
60 // If one IP maps to multiple hostnames, we concatenate the hostnames (separated by a delimiter)
61 secondSrc = secondHostnames.stream().collect(Collectors.joining(delimiter));
64 return String.format("%d, %d, %s, %s", packetPair.getFirst().getOriginalLength(),
65 packetPair.getSecond().getOriginalLength(), firstSrc, secondSrc);