我正在尝试通过从客户端发送到服务器的结构。结构看起来像这样:
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);
打印出来我得到正确的输出
然后我调用send将结构传递给服务器
send(socketfd, &person, sizeof(&person), 0);
在服务器方面,它使用recv读取一个人:
Person person;
recv(newSocketfd, &person, sizeof(Person), 0);
打印出字段,它没有给我我期望的输出......
我做过研究,似乎只要我没有通过结构传递指针我应该能够做到这一点。我对此不正确吗?任何帮助将不胜感激。
答案 0 :(得分:1)
sizeof(&person)
(在发送中)是Person地址的大小。不是Person
结构的大小。试试sizeof(Person)
。