18
18
19
19
import java .io .IOException ;
20
20
import java .io .PrintWriter ;
21
+ import java .net .Inet4Address ;
22
+ import java .net .Inet6Address ;
23
+ import java .net .InetAddress ;
21
24
import java .nio .charset .StandardCharsets ;
22
25
import java .nio .file .Files ;
23
26
import java .nio .file .Path ;
@@ -40,9 +43,22 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc
40
43
String instanceId =
41
44
System .getenv ().containsKey ("GAE_MODULE_INSTANCE" )
42
45
? 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
+ }
44
56
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 );
46
62
StringBuffer sb = new StringBuffer ();
47
63
List <String > strings = Files .readAllLines (tmpFile , StandardCharsets .US_ASCII );
48
64
for (String s : strings ) {
0 commit comments