通过Windows套接字在C中发送整数

时间:2020-10-17 10:09:26

标签: c windows sockets integer winsock

我正在尝试通过C以网络形式发送一个整数(更具体地说,<hello name="{{ name }}"></hello> <p> Start editing to see some magic happen :) </p> {{ngForm.submitted | json }} <form #ngForm="ngForm" [formGroup]="profileForm" (ngSubmit)="onSubmit()"> <label> First Name: <input type="text" formControlName="firstName"> </label> <label> Last Name: <input type="text" formControlName="lastName"> </label> </form> <button type="button" (click)="submitForm()">trigger submit outside</button> 个字节)。我相信我会根据Stack Overflow上的其他示例和答案正确发送数据;但是,在接收字节时,我很难将它们转换/转换为uint32_t。这是我尝试的一个示例:

发件人:

uint32_t

接收器:

    uint32_t num = htonl(100);
    char* converted_num = (char*)&num;
    send(client_sock, converted_num, sizeof(num), 0);

接收器输出大整数 char buf[8192]; recv(socket, buf, 8192, 0); uint32_t test = ntohl((uint32_t)&buf); printf("%d\n", (int)test); ,而不是正确的整数值“ 100”。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

您正在将指针转换为无效的整数。 *(uint32_t*)&buf如果幸运的话,可能可以工作,但是由于严格的别名冲突,它的行为未定义C。

为正确起见,您应该首先将memcpy应用于uin32_t,然后对其应用nthol

static inline uint32_t ntohl_ch(char const *X)
{
    uint32_t x; memcpy(&x,X,sizeof(x));
    return ntohl(x);
}

//...
    uint32_t test = ntohl_ch(&buf[0]);
//...

严格的别名允许您将任何对象视为char(或signed charunsigned char)的数组。反之则不成立。禁止在uint32_t数组中想象char,而必须使用memcpy

优化编译器会注意到您memcpy只是uint32_t,并且取消了完整的memcpy调用(建议直接使用mov进行注册或直接使用原始内存上的汇编指令。

答案 1 :(得分:-1)

在这一行

    uint32_t test = ntohl((uint32_t)&buf);

您正在转换并打印指向buf的指针,而不是接收到的数据。 取消引用指针以获得接收到的内容。

    uint32_t test = ntohl(*(uint32_t*)&buf);
相关问题