简体   繁体   English

如何以十六进制修改地址 ip?

[英]How to modify an adress ip in hex?

I am displaying adress ip of some network nodes with using a network simulator, But I don't have the expected result.我正在使用网络模拟器显示一些网络节点的地址 ip,但我没有预期的结果。

I display ip adress with using this function:我使用此功能显示 ip 地址:

void print_hex_src_adress(uint8_t *s, size_t len)
{
    printf("  ID=");
    for(int i=0; i< len; i++) {
        printf("%02x", s[i]);
    }
}

Then in order to display the adress I put:然后为了显示我放的地址:

open_addr_t * myaddress;
myaddress = idmanager_getMyID(ADDR_64B);
print_hex_src_adress(myadress, 16);

But the result that I have is not the expected result:但我得到的结果不是预期的结果:

  ID=02141592cc0000000400000093947ae2

the expected result is:预期结果是:

  ID=02141592cc0000000400000000000000

idmanager_getMyID returns a pointer to a union of type open_addr_t . idmanager_getMyID返回一个指向open_addr_t类型联合的指针。 A union is an object big enough to hold any of the fields it could contain.联合是一个足够大的对象,可以容纳它可能包含的任何字段。 That does not mean that all the data in it will be initialized.这并不意味着其中的所有数据都将被初始化。 You are requesting ADDR_64B , which means that only the first 64 bits, or 8 bytes, of the union are likely to be initialized via the addr_64b field.您正在请求ADDR_64B ,这意味着只有前 64 位或 8 个字节的联合可能会通过addr_64b字段进行初始化。

What is effectively happening is that you are invoking undefined behavior, trying to print bytes that contain trash values.实际发生的是您正在调用未定义的行为,试图打印包含垃圾值的字节。 The good news is that you won't run into memory that you aren't allowed to use because the union is at least 16 bytes.好消息是您不会遇到不允许使用的内存,因为联合至少为 16 个字节。 You are expecting the trash to be zeros, but instead are getting actual trash.您期望垃圾为零,但实际上却得到了垃圾。 You have two options:您有两个选择:

  1. Print the bytes you actually requested:打印您实际请求的字节:

     print_hex_src_adress(myadress.addr_64b, sizeof(myadress.addr_64b));

    Using sizeof for something like this is a good habit to have.对这样的事情使用sizeof是一个好习惯。 Structures and unions can change between versions, but writing it like this makes your code mode robust against such changes.结构和联合可以在不同版本之间改变,但是这样编写可以使您的代码模式对此类更改具有健壮性。

  2. Request the bytes you actually want:请求你真正想要的字节:

     myaddress = idmanager_getMyID(ADDR_128B);

    Still refer to the correct field when you print, and don't hard-code the size so much:打印时仍然参考正确的字段,并且不要对大小进行太多硬编码:

     print_hex_src_adress(myadress.addr_128b, sizeof(myadress.addr_128b));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM