Created
November 11, 2015 21:57
-
-
Save NateBrune/bf44b4956a33178fd09a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Simple socket server using threads | |
''' | |
import socket | |
import sys | |
from thread import * | |
HOST = '' # Symbolic name meaning all available interfaces | |
PORT = 1347 # Arbitrary non-privileged port | |
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) | |
print 'Socket created' | |
#Bind socket to local host and port | |
try: | |
s.bind((HOST, PORT)) | |
except socket.error as msg: | |
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] | |
sys.exit() | |
print 'Socket bind complete' | |
#Start listening on socket | |
s.listen(10) | |
print 'Socket now listening' | |
#Function for handling connections. This will be used to create threads | |
def clientthread(conn): | |
#Sending message to connected client | |
conn.send('Welcome to Nathanials hping.\nEnter the IP you would like to ping: ') #send only takes string | |
ip = conn.recv(1024) | |
if not ip: | |
conn.send('\nWe are done here.\n') | |
conn.close() | |
conn.send('\n(optional) port: ') #send only takes string | |
port = conn.recv(1024) | |
if not port: | |
conn.send('\nOkay, no port, I get it, no big deal. Dont freak out. Its cool. Seriously. No port hasnt been implemented yet. Hit me up when you got a port though.\n') | |
conn.close() | |
try: | |
ipcon=socket.socket(socket.AF_INET6, socket.SOCK_STREAM) | |
ipcon.bind(("",0)) | |
print "connecting to: " + str(ip)[:-2] + ":" + str(port) | |
ipcon.connect((ip[:-2],int(port))) | |
conn.send('\nI found a service running on that port!\n') | |
conn.close() | |
except all as msg: | |
print "exception " + msg | |
conn.send('\nI have some bad news. We tried as hard as we could.\nThe service wasnt visible.\nI am sorry.') | |
conn.close() | |
#came out of loop | |
conn.close() | |
#now keep talking with the client | |
while 1: | |
#wait to accept a connection - blocking call | |
conn, addr = s.accept() | |
print 'Connected with ' + addr[0] + ':' + str(addr[1]) | |
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. | |
start_new_thread(clientthread ,(conn,)) | |
s.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment