Unable to write a method in Java to find a list of unique IP address from a text file? [closed]

StackOverflow https://stackoverflow.com/questions/23166739

  •  06-07-2023
  •  | 
  •  

Question

LogEntry [date=2010-03-24, time=07:24:28, siteName=ZZZZC941948879, computerName=RUFFLES, sIpAddress=GET, csMethod=222.222.222.222, csUriStem=/img/bg-top.jpg, csUriQuery=-, sPort=80, csUsername=-, csIpAddress=207.49.55.29, csVersion=HTTP/1.1, csUserAgent=Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+9.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+9.0;+MS-

here is my code :

public int countDistinctClientIPAddresses() {
    try {
        readLogFile();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    LogEntry[] temp = new LogEntry [1000];

    int counts = 0;
    for (int k = 0; k < count; k++) {
        if (!entryLog[0].getCsIpAddress().equals(
                entryLog[k].getCsIpAddress())) {
            entryLog[0] = temp[0];
            counts++;
        } else{
            for (int a = 0; a < count; a++){
                if (entryLog[0].getCsIpAddress().equals(
                        entryLog[k].getCsIpAddress())) {
                    entryLog[0] = temp[a];
                    counts--;

            }
            }

    }

    }
    return counts;
}
// basically I want to get a distinct ip addresses from a text logfile in which

there are heaps of identical ip addresses . I am getting an error null pointer exception, My lecturer asked me to make a new array temp and put the ip addressed into it so than i will not put the next identical address into it, and that count of array will me my answer but m stuck, my output is coming wrong like 688 unique address but there are lot of same addresses so there must be less unique addresses help me please.

Was it helpful?

Solution

As I understand entryLog values you get from readLogFile(). So you can use java.util.Set to get list of unique IP addresses:

public int countDistinctClientIPAddresses() {
    try {
        readLogFile();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Set<String> uniqueIPs = new HashSet<String>();
    for (int k = 0; k < count; k++) {
        uniqueIPs.add(entryLog[k].getCsIpAddress());
    }

    return uniqueIPs.size();
}

OTHER TIPS

If you can use collections you can try this

public int countDistinctClientIPAddresses() {
    try {
        readLogFile();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Set<String> entries = new HashSet<String>();
    for (LogEntry e : entryLog){
        entries.add(e.getCsIpAddress());
    }
    return entries.size();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top