brsanthu / google-analytics-java

Java API for Google Analytics Measurement Protocol (part of Universal Analytics).
133 stars 68 forks source link

Anonymize IP addresses client-side #57

Open robertvazan opened 5 years ago

robertvazan commented 5 years ago

I am using this library server-side, proxying analytics data from the client. I want to anonymize IP addresses before sending them to GA. I am currently doing this:

/*
 * Perform local IP address anonymization.
 * We are also instructing GA to anonymize IPs on GA end,
 * but it is technically and legally safer to anonymize locally.
 * Anonymization rules are the same as those used by GA,
 * i.e. zero last 80 bits of IPv6 and last 8 bits of IPv4.
 */
InetAddress ip = InetAddress.getByName("12.34.56.78");
byte[] address = ip.getAddress();
int anonymizedBytes = ip instanceof Inet6Address ? 10 : 1;
for (int i = 0; i < anonymizedBytes; ++i)
    address[address.length - i - 1] = 0;
return InetAddress.getByAddress(address).getHostAddress();

I guess many people could use IP anonymization for compliance reasons. It would give your library a privacy edge. Consider adding this as an option. Thanks.

brsanthu commented 5 years ago

Added the feature into library via setAnonymizeUserIp config flag.