0

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: ")
2
  • What actually happens? Commented Jun 16, 2014 at 8:42
  • Are you sure addr is a string containing the IP? maybe it is a tuple that contains the couple (address,port) Commented Jun 16, 2014 at 8:44

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

'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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.