-2

I am using some code out of a book for NetSec, but there is one line I cannot figure out. I am knowledgeable of Python 3, but not 2, which is what this book is eccentric upon.

The code is:

client,addr = server.accept()

To be quite frank, what the hell does this mean? The entire code for the project is here:

import socket
import threading

ip = "192.168.0.155"
port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((ip, port))

server.listen(5)

print "* Listening on %s:%d" %(ip,port)

def handle_client(client_socket):

    request = client_socket.recv(1024)
    print "* Received %s" % request
client,addr = server.accept()
    client_socket.send("Received: %s" % request)


client,addr = server.accept()
    client_socket.send("Received: %s" % request)
    client_socket.close()
    for each in request:
        print each

while True:
    client,addr = server.accept()
    print "* Received connection from %s:%d" % (addr[0], addr[1])
    client_handler = threading.Thread(target=handle_client, args=(client,))
    client_handler.start()
Colby Cox
  • 217
  • 1
  • 2
  • 7

2 Answers2

2

That's called sequence unpacking. server.accept() returns a tuple (socket, address), which is unpacked into the two variables client and addr.

It's equivalent to

temp= server.accept()
client= temp[0]
addr= temp[1]

More info in the docs.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
1

server.accept() is returning a tuple, and the values of that tuple are being assigned to client and addr respectively. A simplified example:

> x,y = (1,2)
> print(x)
1
> print(y)
2

This is a very common idiom in Python, and I don't think it's any different in Python 3.


Edit Regarding the trailing comma in ...args=(client,))
see here: Python tuple trailing comma syntax rule

Community
  • 1
  • 1
lemondifficult
  • 231
  • 3
  • 15