Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sockets Peer to Peer

I'm trying to make a simple Peer to Peer Network in Python 2.7. The problem is, I can't seem to be able to create a connection between two machines in which they both act as a server and a client. I can get it to work when one is a server and the other is a client but not when they are both, both. Do I need to create 2 sockets? Also I'm using TCP to connect.

UPDATE:

import socket, sys               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

if sys.argv[1] == "connect":
    host = sys.argv[2]
    s.connect((host, port))
    s.close 
else:
    s.listen(5)                 # Now wait for client connection.
    while True:
       c, addr = s.accept()     # Establish connection with client.
       print 'Got connection from', addr
       c.send('Thank you for connecting')
       c.close()

The codes not very good because for someone to connect as a client they have to use the argument "connect" followed by the hostname or IP of the second machine. I can't get the two to connect and serve to each other simultaneously.

like image 903
user3566150 Avatar asked Apr 24 '14 11:04

user3566150


People also ask

Is Python good for socket programming?

Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.

What are Python sockets used for?

Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC).


1 Answers

Yes, two sockets are necessary. The listening socket should open on a constant port, and the client port should be opened on a different (potentially dynamic) port, usually higher in the port range. As an example:

Server sockets on port 1500, client sockets on port 1501.

Peer1: 192.168.1.101

Peer2: 192.168.1.102

When peer1 connects to peer2 it looks like this: 192.168.1.101:1501 -> 192.168.1.102:1500.

When peer2 connects to peer1 it looks like this: 192.168.1.102:1501 -> 192.168.1.101:1500.

Listening TCP sockets are also generally run on a separate thread since they are blocking.

like image 110
Chase Adams Avatar answered Oct 06 '22 21:10

Chase Adams