Skip to content

Commit 1085480

Browse files
committed
Merge pull request #160 from GoogleCloudPlatform/ip
Using only the first 2 octets of IP addresses.
2 parents b00f1dc + 3a8b127 commit 1085480

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

managed_vms/cloudsql/main.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import datetime
1616
import os
17+
import socket
1718

1819
from flask import Flask, request
1920
from flask.ext.sqlalchemy import SQLAlchemy
@@ -22,6 +23,15 @@
2223
app = Flask(__name__)
2324

2425

26+
def is_ipv6(addr):
27+
"""Checks if a given address is an IPv6 address."""
28+
try:
29+
socket.inet_pton(socket.AF_INET6, addr)
30+
return True
31+
except socket.error:
32+
return False
33+
34+
2535
# [START example]
2636
# Environment variables are defined in app.yaml.
2737
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']
@@ -41,8 +51,16 @@ def __init__(self, timestamp, user_ip):
4151

4252
@app.route('/')
4353
def index():
54+
user_ip = request.remote_addr
55+
56+
# Keep only the first two octets of the IP address.
57+
if is_ipv6(user_ip):
58+
user_ip = ':'.join(user_ip.split(':')[:2])
59+
else:
60+
user_ip = '.'.join(user_ip.split('.')[:2])
61+
4462
visit = Visit(
45-
user_ip=request.remote_addr,
63+
user_ip=user_ip,
4664
timestamp=datetime.datetime.utcnow()
4765
)
4866

managed_vms/datastore/main.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
import datetime
16+
import socket
1617

1718
from flask import Flask, request
1819
from gcloud import datastore
@@ -21,14 +22,31 @@
2122
app = Flask(__name__)
2223

2324

25+
def is_ipv6(addr):
26+
"""Checks if a given address is an IPv6 address."""
27+
try:
28+
socket.inet_pton(socket.AF_INET6, addr)
29+
return True
30+
except socket.error:
31+
return False
32+
33+
2434
# [START example]
2535
@app.route('/')
2636
def index():
2737
ds = datastore.Client()
2838

39+
user_ip = request.remote_addr
40+
41+
# Keep only the first two octets of the IP address.
42+
if is_ipv6(user_ip):
43+
user_ip = ':'.join(user_ip.split(':')[:2])
44+
else:
45+
user_ip = '.'.join(user_ip.split('.')[:2])
46+
2947
entity = datastore.Entity(key=ds.key('visit'))
3048
entity.update({
31-
'user_ip': request.remote_addr,
49+
'user_ip': user_ip,
3250
'timestamp': datetime.datetime.utcnow()
3351
})
3452

0 commit comments

Comments
 (0)