Skip to content

Commit

Permalink
Merge pull request #160 from GoogleCloudPlatform/ip
Browse files Browse the repository at this point in the history
Using only the first 2 octets of IP addresses.
  • Loading branch information
lesv committed Jan 29, 2016
2 parents b00f1dc + 3a8b127 commit 1085480
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
20 changes: 19 additions & 1 deletion managed_vms/cloudsql/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import datetime
import os
import socket

from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
Expand All @@ -22,6 +23,15 @@
app = Flask(__name__)


def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False


# [START example]
# Environment variables are defined in app.yaml.
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']
Expand All @@ -41,8 +51,16 @@ def __init__(self, timestamp, user_ip):

@app.route('/')
def index():
user_ip = request.remote_addr

# Keep only the first two octets of the IP address.
if is_ipv6(user_ip):
user_ip = ':'.join(user_ip.split(':')[:2])
else:
user_ip = '.'.join(user_ip.split('.')[:2])

visit = Visit(
user_ip=request.remote_addr,
user_ip=user_ip,
timestamp=datetime.datetime.utcnow()
)

Expand Down
20 changes: 19 additions & 1 deletion managed_vms/datastore/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import datetime
import socket

from flask import Flask, request
from gcloud import datastore
Expand All @@ -21,14 +22,31 @@
app = Flask(__name__)


def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False


# [START example]
@app.route('/')
def index():
ds = datastore.Client()

user_ip = request.remote_addr

# Keep only the first two octets of the IP address.
if is_ipv6(user_ip):
user_ip = ':'.join(user_ip.split(':')[:2])
else:
user_ip = '.'.join(user_ip.split('.')[:2])

entity = datastore.Entity(key=ds.key('visit'))
entity.update({
'user_ip': request.remote_addr,
'user_ip': user_ip,
'timestamp': datetime.datetime.utcnow()
})

Expand Down

0 comments on commit 1085480

Please sign in to comment.