How can I prevent unauthorized connections to my python socket server?
<p>I have a simple server written in python that opens and listens on a TCP socket:</p>

<pre><code>import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 4242)) server_socket.listen(5)

print("TCPServer Waiting for client on port 4242")

while 1:
    client_socket, address = server_socket.accept()
    print("I got a connection from ", address)
    while 1:
        data = client_socket.recv(512)
        if data:
            print(data)
        if not data:
            print("Closed Connection")
            break
</code></pre>

<p>and it works great!</p>

<p>I am now left wondering... any rouge client can connect to my server if they know my IP and port.  Given that my IP and port aren't crazy secure... how can I make sure that the only device that can connect to this TCP socket is my own device?</p>

<p>Can I make some sort of key?  Is that what SSL is about, I am having trouble understanding that.  It seems like SSL just protects the data from being intercepted, but anyone can still connect and write to my listener?</p>

<p>Thanks!</p>

<p>You don't need SSL here. TSL and SSL are protocols that provide an encrypted communication over a network, so even if someone is 'listening'  to that communication, they can't understand it.</p>

<p>The accept() method returns a tuple (conn, <em>address</em>) (<a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a>)</p>

<p>You could choose to drop that connection (don't recive any data) if <em>address</em> doesn't match your IP address.</p>

<pre><code>if address == your_ip
    # receive data
</code></pre>

<p>If you don't want to do it programmatically, under Linux, you could use some packet filtering tool like iptables.</p>

<pre><code>$ iptables -I INPUT -p tcp --destination-port 4242 -s &lt;range_of_blocked_ip_addresses&gt; -j DROP
</code></pre>

python sockets tcp