python - 发送缓冲区的长度并使用 C 从 python 接收它

标签 python c struct

我正在使用这个简单的 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 - 发送缓冲区的长度并使用 C 从 python 接收它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734381/

相关文章:

swift - 是否可以像在 Swift 中使用数组/字典那样遍历结构中的值?

python - ImportError:没有名为 Shell 的模块; shell 未导入(32 位,python)

python - 为什么 `myfloat in myset` 变得 super 慢?

c - 为什么我的程序返回我没有输入的字符? (纯C)

c - 如何防止子进程中的 SIGINT 传播到父进程并杀死父进程?

ios - 使用最新的 iOS SDK 编译时,libcurl 在 iOS 9 上崩溃

c++ - 在类或结构中使用运算符?

c++ - 在 std::map 中存储结构实例

python - 我应该使用哪种布局在 python 中的 igraph 中获得非重叠边缘?

python - DataFrame 列包含双引号内的列表