1818
1919import java .io .IOException ;
2020import java .io .PrintWriter ;
21+ import java .net .Inet4Address ;
22+ import java .net .Inet6Address ;
23+ import java .net .InetAddress ;
2124import java .nio .charset .StandardCharsets ;
2225import java .nio .file .Files ;
2326import java .nio .file .Path ;
@@ -40,9 +43,22 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc
4043 String instanceId =
4144 System .getenv ().containsKey ("GAE_MODULE_INSTANCE" )
4245 ? System .getenv ("GAE_MODULE_INSTANCE" ) : "1" ;
43- String userId = req .getRemoteAddr () + "\n " ;
46+ // store only the first two octets of a users ip address
47+ String userIp = req .getRemoteAddr ();
48+ InetAddress address = InetAddress .getByName (userIp );
49+ if (address instanceof Inet6Address ) {
50+ // nest indexOf calls to find the second occurrence of a character in a string
51+ // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
52+ userIp = userIp .substring (0 , userIp .indexOf (":" , userIp .indexOf (":" ) + 1 )) + ":*:*:*:*:*:*" ;
53+ } else if (address instanceof Inet4Address ) {
54+ userIp = userIp .substring (0 , userIp .indexOf ("." , userIp .indexOf ("." ) + 1 )) + ".*.*" ;
55+ }
4456 Path tmpFile = Paths .get ("/tmp/seen.txt" );
45- Files .write (tmpFile , userId .getBytes (), StandardOpenOption .CREATE , StandardOpenOption .APPEND );
57+ Files .write (
58+ tmpFile ,
59+ (userIp + "\n " ).getBytes (),
60+ StandardOpenOption .CREATE ,
61+ StandardOpenOption .APPEND );
4662 StringBuffer sb = new StringBuffer ();
4763 List <String > strings = Files .readAllLines (tmpFile , StandardCharsets .US_ASCII );
4864 for (String s : strings ) {
0 commit comments