发送缓冲区的长度并使用 C 从 python 接收它
sending the length of the buffer and receive it with C from python
我正在使用这个简单的 python 服务器代码来发送缓冲区的长度
我即将发送:
def server_mode(ip, port):
try:
s = socket()
s.bind((ip, port))
print ("[*] Listening on %s:%d\n[*] Waiting for clients" % (ip, port))
if ("win32" == os.sys.platform):
print("[*] Press Ctrl + Break to stop server")
elif ("linux" in os.sys.platform):
print("[*] Press Ctrl + C to stop server")
while True:
s.listen(MAX_CLIENTS)
client, client_ip = s.accept()
client_ip = client_ip[0]
print("[*] Got connection from %s" % client_ip)
buf = struct.pack(">I", 7313)
client.send(buf)
client.close()
except KeyboardInterrupt:
s.close()
print("[*] Closed socket")
exit()
except:
s.close()
raise
然后使用此 C 代码,客户端应接收缓冲区的长度
我即将发送并分配缓冲区所需的位置并接收它:
char* buf = malloc(4 * sizeof(char));
recv(sockfd, buf, 4, 0);
int buf_len = *buf;
它可以工作,但只转换 4 字节 long int 的前两个字节,
例如,如果我用它发送大小为 13 的 len
缓冲区,它会很好地接收它,但在像 7313 这样的数字上它会收到 54.
这个:
int buf_len = *buf;
不会从 buf
神奇地读取 sizeof buf_len
(你似乎期望它是四个)字节,因为 *buf
是类型 char
的值。
你应该使用 uint8_t
而不是 char
,uint32_t
而不是 int
,并尽可能多地阅读,当然要尊重字节顺序:
uint8_t buf[4];
if(recv(sockfd, buf, sizeof buf, 0) == 4)
{
const uint32_t buf_len = ((uint32_t) buf[0] << 24) |
((uint32_t) buf[1] << 16) |
((uint32_t) buf[2] << 8) |
buf[3];
...
}
我正在使用这个简单的 python 服务器代码来发送缓冲区的长度 我即将发送:
def server_mode(ip, port):
try:
s = socket()
s.bind((ip, port))
print ("[*] Listening on %s:%d\n[*] Waiting for clients" % (ip, port))
if ("win32" == os.sys.platform):
print("[*] Press Ctrl + Break to stop server")
elif ("linux" in os.sys.platform):
print("[*] Press Ctrl + C to stop server")
while True:
s.listen(MAX_CLIENTS)
client, client_ip = s.accept()
client_ip = client_ip[0]
print("[*] Got connection from %s" % client_ip)
buf = struct.pack(">I", 7313)
client.send(buf)
client.close()
except KeyboardInterrupt:
s.close()
print("[*] Closed socket")
exit()
except:
s.close()
raise
然后使用此 C 代码,客户端应接收缓冲区的长度 我即将发送并分配缓冲区所需的位置并接收它:
char* buf = malloc(4 * sizeof(char));
recv(sockfd, buf, 4, 0);
int buf_len = *buf;
它可以工作,但只转换 4 字节 long int 的前两个字节,
例如,如果我用它发送大小为 13 的 len
缓冲区,它会很好地接收它,但在像 7313 这样的数字上它会收到 54.
这个:
int buf_len = *buf;
不会从 buf
神奇地读取 sizeof buf_len
(你似乎期望它是四个)字节,因为 *buf
是类型 char
的值。
你应该使用 uint8_t
而不是 char
,uint32_t
而不是 int
,并尽可能多地阅读,当然要尊重字节顺序:
uint8_t buf[4];
if(recv(sockfd, buf, sizeof buf, 0) == 4)
{
const uint32_t buf_len = ((uint32_t) buf[0] << 24) |
((uint32_t) buf[1] << 16) |
((uint32_t) buf[2] << 8) |
buf[3];
...
}