调过来在C座整 [英] transfer integer over a socket in C

查看:98
本文介绍了调过来在C座整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是转移的适当方法的 INT 过在C插座?结果
我在做什么,到目前为止是:

  INT N = 4;
INT TMP = htonl(N);
写(插座,&安培; TMP,的sizeof(TMP));

  INT TMP,N;
阅读(插座,&安培; TMP,的sizeof(TMP));
N = ntohl(TMP);

但是,收到的整数有时是0并非总是如此,但假设2出5倍。这是从来没有一些其他的价值,始终为0。为什么?

更新:从读返回值为-1,而一个错误是:

 资源暂时不可用


解决方案

首先,sizeof的(INT)可以在您的发送者和接收者的机器不同。因此,我建议你使用类似int32_t从stdint.h。

另外,它不能保证读(..,..,sizeof的(INT))的读出准确的sizeof(int)的字节 - 它可以读取任何或读更少字节。所以,正确的变种会是这样的:

 发送INT(INT NUM,诠释FD)
{
    int32_t兑换= htonl(NUM);
    字符*数据=(字符*)及转换次数;
    INT左= sizeof的(CONV);
    INT RC;
    同时(左){
        RC =写(FD,数据+的sizeof(CONV) - 左,左);
        如果(RC℃下)返回-1;
        左 - = RC;
    }
    返回0;
}
INT接收(INT * NUM,诠释FD)
{
    int32_t RET;
    字符*数据=(字符*)及RET;
    INT左= sizeof的(RET);
    INT RC;
    同时(左){
        RET =读(FD,数据+的sizeof(RET) - 左,左);
        如果(RET℃下)返回-1;
        左 - = RET;
    }
    * NUM = RET;
    返回0;
}

What is the appropriate way to transfer an int over a socket in C?
What I am doing so far is:

int n = 4;
int tmp = htonl(n);
write(socket, &tmp, sizeof(tmp));

and

int tmp,n;
read(socket, &tmp, sizeof(tmp));
n = ntohl(tmp);

However, the integer received is sometimes 0. Not always, but let's say 2 out of 5 times. It is never some other value, always 0. Why?

UPDATE: Return value from read is -1 and an error is:

Resource temporarily unavailable

解决方案

First of all, sizeof(int) may differ on your sender and receiver machine. So I would recommend you to use something like int32_t from stdint.h.

Also, it is not guaranteed that read(..,..,sizeof(int)) will read exactly sizeof(int) bytes -- it can read nothing or read less bytes. So, the correct variant will be something like:

int send(int num, int fd)
{
    int32_t conv = htonl(num);
    char *data = (char*)&conv;
    int left = sizeof(conv);
    int rc;
    while (left) {
        rc = write(fd, data + sizeof(conv) - left, left);
        if (rc < 0) return -1;
        left -= rc;
    }
    return 0;
}
int receive(int *num, int fd)
{
    int32_t ret;
    char *data = (char*)&ret;
    int left = sizeof(ret);
    int rc;
    while (left) {
        ret = read(fd, data + sizeof(ret) - left, left);
        if (ret < 0) return -1;
        left -= ret;
    }
    *num = ret;
    return 0;
}

这篇关于调过来在C座整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆