def handle_socks4_negotiation(sock, username=None):
 received_version = sock.recv(1)
 command = sock.recv(1)
 port = _read_exactly(sock, 2)
 port = ((ord(port[0:1]) << 8) + ord(port[1:2]))
 addr = _read_exactly(sock, 4)
 provided_username = _read_until(sock, '\x00')[:(-1)]
 if (addr == '\x00\x00\x00\x01'):
  addr = _read_until(sock, '\x00')[:(-1)]
 else:
  addr = socket.inet_ntoa(addr)
 assert (received_version == SOCKS_VERSION_SOCKS4)
 assert (command == '\x01')
 if ((username is not None) and (username != provided_username)):
  sock.sendall('\x00]\x00\x00\x00\x00\x00\x00')
  sock.close()
  (yield False)
  return
 succeed = (yield (addr, port))
 if succeed:
  response = '\x00Z\xea`\x7f\x00\x00\x01'
 else:
  response = '\x00[\x00\x00\x00\x00\x00\x00'
 sock.sendall(response)
 (yield True)

def handle_socks4_negotiation ( sock , username = None ) : received_version = sock . recv ( 1 ) command = sock . recv ( 1 ) port = _read_exactly ( sock , 2 ) port = ( ( ord ( port [ 0 : 1 ] ) << 8 ) + ord ( port [ 1 : 2 ] ) ) addr = _read_exactly ( sock , 4 ) provided_username = _read_until ( sock , '\x00' ) [ : ( - 1 ) ] if ( addr == '\x00\x00\x00\x01' ) : addr = _read_until ( sock , '\x00' ) [ : ( - 1 ) ] else : addr = socket . inet_ntoa ( addr ) assert ( received_version == SOCKS_VERSION_SOCKS4 ) assert ( command == '\x01' ) if ( ( username is not None ) and ( username != provided_username ) ) : sock . sendall ( '\x00]\x00\x00\x00\x00\x00\x00' ) sock . close ( ) ( yield False ) return succeed = ( yield ( addr , port ) ) if succeed : response = '\x00Z\xea`\x7f\x00\x00\x01' else : response = '\x00[\x00\x00\x00\x00\x00\x00' sock . sendall ( response ) ( yield True )
handle the socks4 handshake .