Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

converters - C Coding :: Convert IPv4 Array to u_int32_t?

I recently wrote C code using a library. That library previously defined IPv4 addresses as an 1D array of u_int8_t’s. If I wanted to represent IP address 10.20.30.40, for example, it was pretty simple:

u_int8_t ipv4Array[4];         // Defined in the library

// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// My code:

void printIP( u_int8_t* x ){
        printf(">> %d.%d.%d.%d
", x[0], x[1], x[2], x[3]);
}

void foo(){
        u_int8_t* myIP = (u_int8_t*) malloc( sizeof(ipv4Array) );
        myIP[0] = 10;
        myIP[1] = 20;
        myIP[2] = 30;
        myIP[3] = 40;

        printIP( myIP );

        free( myIP );
}

Output was:

>> 10.20.30.40

Very simple, and I liked things this way. However, the authors of the library released an update where IPv4 addresses are now represented as u_int32_t. I’m uncertain how to modify my code. Here’s my best stab:

u_int32_t* ipv4;           // *New* definition in the library

// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// My code:

void foo(){
        ipv4 = (u_int32_t*) malloc( sizeof(u_int32_t) );
        bzero( ipv4, sizeof(u_int32_t) );

        *ipv4 += 10<<24;
        *ipv4 += 20<<16;
        *ipv4 += 30<<8;
        *ipv4 += 40;

        printf(">> %u
", *ipv4);

        free( ipv4 );
}

Output is:

>> 169090600

So I’m happy to see that:

Decimal:  169090600

Binary:   0000 1010  0001 0100  0001 1110  0010 1000
              10         20         30         40

Which suggests that my hack is correct. But I’m nervous to plug this into production code without checking first. Can anyone see an issue with my solution? All criticism is welcome.

question from:https://stackoverflow.com/questions/65887656/c-coding-convert-ipv4-array-to-u-int32-t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...