Louis Bernard
Louis Bernard

Reputation: 279

Python: Only accept specific IP (socket)

I have a program that consists of a java client and a python server. The python server can recieve multiple connections and the clients will try to connect to the server every 17 seconds. My question: The server should only accept one connection with the IP the user typed in before.

HOST = '0.0.0.0'
PORT = 1979

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'

try:
        s.bind((HOST, PORT))
except socket.error as e:
    print(e)
        sys.exit()

print 'Socket bind complete'

s.settimeout(30)
s.listen(10)

print 'Listening...'

timeout = 8

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    try:
            conn, addr = s.accept()
        msg = conn.recv(1024)
        print ('--------------------------------------')
        print (msg) 
    except socket.timeout as e:
        print(e,': No client out there :(')
        s.close()
        break

        print 'Client connected: ' + addr[0] + ':' + str(addr[1])
    print ('--------------------------------------')

s.close()   

This socket accepts all incoming connections. I want to add this before the socket:

connectip = raw_input('Please enter the IP of the client you want to connect to ')

and then the socket should only accept the client with the IP the user specified in "connectip".

Please pardon my bad english

Upvotes: 2

Views: 2987

Answers (1)

dangee1705
dangee1705

Reputation: 3510

You will still have to accept it, but you can close it before you transfer any data.

connectip = raw_input("Please enter the IP of the client you want to connect to ")
conn, addr = s.accept()
if addr[0] != connectip:
    conn.shutdown(SHUT_RDWR)
    conn.close()
else:
    # do what ever you want here

On a side note, you should really be switching to python 3, as python 2 is going to be deprecated very soon.

Upvotes: 5

Related Questions