Home > Blockchain >  An understanding of something in python sockets
An understanding of something in python sockets

Time:06-11

So I have programmed a Socks5 server with help from a youtube video. There is one thing I don't understand and hoping to get help with it.

    def run(self, host, port):
        #gives it specifications, Family ip and TCP
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host, port))
        #ip and port to listen to
        s.listen()

        print("* Socks5 proxy server is running on {}:{}".format(host, port))

        while True:
            #3 way handshake when someone connects - TCP
            conn, addr = s.accept()
            #tupple of ip and port
            print("* new connection from {}".format(addr))
            #calling the handle_client function: handle_client(conn),conn is a socket type
            print(conn)
            t = threading.Thread(target=self.handle_client, args=(conn,))
            t.start()


    def handle_client(self, connection):
        version, nmethods = connection.recv(2)
        # get available methods [0, 1, 2]
        methods = self.get_available_methods(nmethods, connection)
        print(methods)

So what I don't understand in this code is this line: version, nmethods = connection.recv(2). The version is the version of socks which is 5. But the methods I don't understand. methods of what? how does it know how many methods it have and to what thing does it even have methods???? Need help, Thank you!

CodePudding user response:

connection.recv(2) means receive (up to) two bytes (source). So, two bytes are returned, and you're setting version to the value of the first byte, and nmethods to the value of the second byte.

Here's an example:

a = b'hi' # a is a bytes object

b, c = a # b and c are ints

print(b, c)
# output: 104 105

So, as for what version and nmethods mean - that's just something specific to this program I think. I'm not super familiar with sockets though. I would guess that nmethods means "number of methods", considering that it's used in get_available_methods() later. As for how it knows the number of methods, whatever those methods are, you'd just have to see the code that sends that data.

  • Related