#!/usr/bin/env python
import socket
import time
import sys
import subprocess
from multiprocessing import Process

global clientName
global s
clientName = ""

""" Get local inet_ip address """
def getInetIP():
    try:
	socket.gethostbyname(socket.gethostname())
    except socket.error as msg:
        print "Not connected to the interwebs"
        sys.exit(1)
    return socket.gethostbyname(socket.gethostname())

""" http://docs.python.org/2.7/library/socket.html """
""" returns the connection socket and the address connected to (conn, addr) """
def listen_to(host, port):
    for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                  socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open connection'
        conn = None
        addr = None
        return conn, addr
    conn, addr = s.accept()
    return conn, addr
""" returns socket s that is connected to port at ip_connect """

def main():
    port = 9999
    """ set up informatino and give host ip address """
    """ make sure port isnt used """
    print "This machines IP address is " + getInetIP()
    hostname = raw_input("Enter a username : ")
    conn, addr = listen_to(None, port)
    while port > 9000:
        if conn == None or addr == None:
            print 'port', port, 'busy, trying', port - 1
            port =- 1
            conn, addr = listen_to(None, port)  
        else:
            break

    clientName = conn.recv(1024)
    subprocess.call(["clear"])
    print 'Connected to', clientName
    print 'To exit chat, type', repr('.logout') 
    conn.send(hostname) 

    while 1:
        data = conn.recv(1024)
        if not data: 
            print 'connection with ' + clientName + ' closed'
            break
        print clientName + ':' + data
        toSend = raw_input('>')
        if toSend == ".logout": break
        conn.sendall(toSend)
    conn.close()

if __name__ == "__main__":
    main()
    