我正在尝试通过从客户端发送到服务器来发送结构。该结构如下所示:
typedef struct{
int age;
long int id;
char firstName[10];
char lastName[10];
uint32_t somefield;
} Person;
现在,当我填写客户端代码中的字段时:
Person person;
person.age = 52;
person.id = 1234567;
strcpy(person.firstName, "Walter");
strcpy(person.lastName, "White");
inet_pton(AF_INET, "127.0.0.1", &person.somefield);
person.somefield = htonl(person.somefield);
并打印出来,我得到了正确的输出
- 年龄:52
- ID:1234567
- 名字:沃尔特
- 姓氏:怀特
- 某些单位:2130706433
然后我调用 send 将结构传递到服务器
send(socketfd, &person, sizeof(&person), 0);
<小时/>
在服务器端,它使用recv读取一个人:
Person person;
recv(newSocketfd, &person, sizeof(Person), 0);
打印出字段,它没有给我期望的输出......
- 年龄:52
- ID:4197943
- 名字:
- 姓氏:
- 某些单位:4286513152
我已经做了研究,看来只要我不通过结构传递指针,我就应该能够做到这一点。我对此的看法是否有误?任何帮助将不胜感激。
最佳答案
sizeof(&person)
(在发送中)是 Person 地址的大小。不是 Person
结构的大小。尝试sizeof(Person)
。
关于c - 通过发送命令发送结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666781/