get-my-ip.py: Add a script for getting your public IP address
authorW. Trevor King <wking@tremily.us>
Tue, 19 Feb 2013 02:52:13 +0000 (21:52 -0500)
committerW. Trevor King <wking@tremily.us>
Mon, 21 Oct 2013 03:48:54 +0000 (20:48 -0700)
This will help students connect to each other on the LAN during class.
Note that if you ping a host across a NAT, you'll get your IP inside
the NAT, not the NAT's IP.

setup/get-my-ip.py [new file with mode: 0755]

diff --git a/setup/get-my-ip.py b/setup/get-my-ip.py
new file mode 100755 (executable)
index 0000000..286e67f
--- /dev/null
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+
+"""Get your public IP address from a UDP socket connection
+"""
+
+import socket as _socket
+
+
+def get_my_ip(host, port=80):
+    with _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM) as s:
+        s.connect((host, port))
+        return s.getsockname()[0]
+
+
+if __name__ == '__main__':
+    import argparse as _argparse
+
+    parser = _argparse.ArgumentParser(description=__doc__)
+    parser.add_argument(
+        'host', default='software-carpentry.org', nargs='?')
+    parser.add_argument(
+        'port', default=80, type=int, nargs='?')
+
+    args = parser.parse_args()
+
+    print(get_my_ip(host=args.host, port=args.port))