C语言 在c中通过tcp套接字发送结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24703206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:12:45  来源:igfitidea点击:

send struct over tcp socket in c

csocketstcpstruct

提问by user1550036

I've got a struct:

我有一个结构:

typedef     struct {
    char            *typ;
    cid_t           cid;
    unsigned short  nbytes;
    char            *data;
} req_s; 

typedef     struct {
    char            *ip;
    unsigned short  pid;
} cid_t;

and I want to send it over a tcp socket. Is that possible? I've done it with:

我想通过 tcp 套接字发送它。那可能吗?我已经做到了:

req_s answer;
...

if( send(sock, (void*)&answer, sizeof(answer),0) < 0 ) {
    printf("send failed!\n");
}

...

recv ( socketDesc, (void*)&answer, sizeof(answer), 0) >= 0)

but if I want to read rout my struct answer I only get some hieroglyphs

但是如果我想阅读我的结构答案,我只会得到一些象形文字

or is there even a better way to send my data from client to server and back?

或者有没有更好的方法将我的数据从客户端发送到服务器并返回?

采纳答案by user1550036

See here: Passing a structure through Sockets in C. However, in your case, you additionally have pointers insideyour structure, so you will have to write contentsof those pointers to the destination buffer, too.

请参阅此处:通过 C 中的 Sockets 传递结构。然而,在你的情况,你还具有指针里面的结构,所以你必须写内容的指针指向目标缓冲区的了。

回答by Xavier Leclercq

Sending pointers over a network connection is usually not going to work as the data they point to will not be copied across and even if it were it would probably reside at a different memory address. You need to serialize your structs to send them over a network connection.

通过网络连接发送指针通常不会起作用,因为它们指向的数据不会被复制,即使它可能会驻留在不同的内存地址。您需要序列化您的结构以通过网络连接发送它们。