Reputation: 35
I wrote a code to open a socket and then accept the socket and connect it. What is the problem? I want to filter the incoming connection ip. So I wrote a "if" statement for the connecting ip but it wont work. Looking forward for your help!
#!/usr/bin/python
import socket
s = socket.socket() # Create a socket
host = socket.gethostname()
port = 12345 # opening a port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # accept the client
c.send('waiting for connection...')
if '192' in addr: #---->This is what does not work.
print 'Got connection from', addr
c.send('Thank you for connecting')
print 'accepted'
else:
c.close()
print 'blocked.'
print '{0} tried to connect'.format(addr)
print 'a connection was request from', addr
raw_input("Press enter to continue: ")
Upvotes: 0
Views: 1437
Reputation: 10602
As we can see here, addr that you get from s.accept() is a tuple containing the ip adress and the port. To check the ip adress use addr[0]
>>> ip='192.168.1.1'
>>> '192' in ip
True
>>> addr=(ip, 2424)
>>> '192' in addr
False
>>> '192' in addr[0]
True
Upvotes: 1
Reputation: 2818
'addr' in the above code is a tuple containing the IP address and port number of the far end, it will look something like this:
('127.0.0.1', 48223)
For the above:
>>> '127' in addr
False
>>> '127' in addr[0]
True
Hopefully this gives you enough to modify the code.
Upvotes: 0