You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

TCP套接字发送拼接字节数组及字符串转字节问题求助

解决TCP套接字发送PASS命令时的字节拼接问题

Got it, let's work through this issue step by step. The core problem here is that you're trying to mix string objects (your buff variable) with byte literals (like b"PASS "), which Python doesn't allow directly—they're different data types, so you can't just add them together.

Here are two straightforward fixes for this:

方案1:先拼接完整字符串,再编码为字节

This is the cleanest approach. Build the full PASS command as a regular string first, then convert it to bytes using .encode() (default is UTF-8, which works for most cases):

import socket

for buff in the_buffer:  # 注意规范变量名,原代码的"the buffer"建议改为the_buffer
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((target, port))  # connect()无返回值,无需赋值给变量
    sock.recv(2048)
    sock.send(b"USER test\r\n")
    sock.recv(2048)
    # 先拼接完整命令字符串,再编码为字节发送
    pass_command = f"PASS {buff}\r\n"
    sock.send(pass_command.encode())
    sock.send(b"QUIT\r\n")
    sock.close()

方案2:将字符串buff转为字节后再拼接

If you prefer to keep working with byte literals directly, convert buff to bytes first with .encode(), then you can safely concatenate all byte objects:

import socket

for buff in the_buffer:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((target, port))
    sock.recv(2048)
    sock.send(b"USER test\r\n")
    sock.recv(2048)
    # 把buff转成字节后,和其他字节字面量拼接
    sock.send(b"PASS " + buff.encode() + b"\r\n")
    sock.send(b"QUIT\r\n")
    sock.close()

额外小提示

  • 原代码里的conncet = sock.connect(...)是多余的,connect()方法没有返回值,不需要赋值给变量。
  • 建议给缓冲区变量起个无空格的规范名字,比如the_buffer,提升代码可读性。

内容的提问来源于stack exchange,提问作者user10464764

火山引擎 最新活动