Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a socket restricted to localhost connections only

I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0.1 should be accepted. How would I do this (in Python)? And is this a suitable design? Or is there something a little more elegant?

like image 394
Dr. Johnson Avatar asked Jan 25 '10 21:01

Dr. Johnson


People also ask

How do I create a non blocking socket in python?

In Python, you use socket. setblocking(False) to make it non-blocking.

How do you stop a listening socket in python?

To close the connection, break the while loop. Garbage collection will remove the thread or process but join will ensure none get left behind. Persistent sockets close when the user closes them or they timeout.

How do I create a socket connection in Python?

The first step is to import the socket module and then create a socket just like you did while creating a server. Then, to create a connection between the client-server you will need to use the connect() method by specifying (host, port).

What is socket Sock_stream?

SOCK_STREAM. Provides sequenced, two-way byte streams with a transmission mechanism for stream data. This socket type transmits data on a reliable basis, in order, and with out-of-band capabilities. In the UNIX domain, the SOCK_STREAM socket type works like a pipe.


1 Answers

Given a socket created with socket.socket(), you can use bind() before listening:

socket.bind(('127.0.0.1', 80))

Using the address 127.0.0.1 indicates that the socket should bind to the local interface only.

like image 189
Greg Hewgill Avatar answered Sep 28 '22 23:09

Greg Hewgill