#!/usr/bin/env python
from threading import Thread
from os import system
from sys import argv
from socket import inet_aton
from ipcalc import Network

def usage():
	print("Usage: " + argv[0] + " <subnet>")
	exit(1)

def ping_ip(host, dictionary):
	response = system("ping -c 1 -w 2 " + host + " > /dev/null 2>&1")
	if response == 0:
		dictionary[host] = True

def main():
	# Check args.
	if len(argv) < 2:
		usage()

	# Set up dictionary of IPs.
	ip_table = {}
	for i in Network(argv[1]):
		ip_table[str(i)] = False

	# Run the threads
	for key in ip_table:
		t = Thread(target=ping_ip, args=(key,ip_table))
		t.start()

	# Sort by IP using socket function inet_aton.
	sorted_table = sorted(ip_table.items(), key=lambda item: inet_aton(item[0]))
	for k in sorted_table:
		if k[1] == True:
			print(k[0])

if __name__ == "__main__":
	main()
