|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2019 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""A simple Hello World type app which can serve on port 8000. |
| 17 | +Optionally, a different port can be passed. |
| 18 | +
|
| 19 | +The code was inspired by: |
| 20 | +https://gist.github.com/davidbgk/b10113c3779b8388e96e6d0c44e03a74 |
| 21 | +""" |
| 22 | +import http |
| 23 | +import http.server |
| 24 | +import socket |
| 25 | +import socketserver |
| 26 | +import sys |
| 27 | + |
| 28 | +# TCP port for listening to connections, if no port is received |
| 29 | +DEFAULT_PORT=8000 |
| 30 | + |
| 31 | +class Handler(http.server.SimpleHTTPRequestHandler): |
| 32 | + def do_GET(self): |
| 33 | + self.send_response(http.HTTPStatus.OK) |
| 34 | + self.end_headers() |
| 35 | + # Hello message |
| 36 | + self.wfile.write(b'Hello Cloud') |
| 37 | + # Now get the hostname and IP and print that as well. |
| 38 | + hostname = socket.gethostname() |
| 39 | + host_ip = socket.gethostbyname(hostname) |
| 40 | + self.wfile.write( |
| 41 | + '\n\nHostname: {} \nIP Address: {}'.format( |
| 42 | + hostname, host_ip).encode()) |
| 43 | + |
| 44 | + |
| 45 | +def main(argv): |
| 46 | + port = DEFAULT_PORT |
| 47 | + if len(argv) > 1: |
| 48 | + port = int(argv[1]) |
| 49 | + |
| 50 | + web_server = socketserver.TCPServer(('', port), Handler) |
| 51 | + print("Listening for connections on port {}".format(port)) |
| 52 | + web_server.serve_forever() |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + main(sys.argv) |
0 commit comments