简体   繁体   中英

Using inet_pton() to get unsigned int representation of IPv4 address

I am trying to convert an IPv4 address from std::string to it's unsigned int representation (according to this ) in C++ (Windows)

I managed to do that with the following code:

void strIPtoUnsignedIntIP(string ipStr){
    struct sockaddr_in ip4addr;

    ip4addr.sin_family = AF_INET;
    inet_pton(AF_INET, ipStr.c_str(), &ip4addr.sin_addr);

    unsigned int resIp = (ip4addr.sin_addr.S_un.S_un_b.s_b1 << 24) + 
                         (ip4addr.sin_addr.S_un.S_un_b.s_b2 << 16) + 
                          (ip4addr.sin_addr.S_un.S_un_b.s_b3 << 8) + 
                                  ip4addr.sin_addr.S_un.S_un_b.s_b4;
    cout << resIp << endl;

}

I am getting the right values, but, the following line is not so elegant:

unsigned int resIp = (ip4addr.sin_addr.S_un.S_un_b.s_b1 << 24) +
                     (ip4addr.sin_addr.S_un.S_un_b.s_b2 << 16) +
                      (ip4addr.sin_addr.S_un.S_un_b.s_b3 << 8) + 
                              ip4addr.sin_addr.S_un.S_un_b.s_b4;

I was hoping that instead of using S_un_b field of sin_addr and then perform the calculation, I could simply take the S_addr field. Unfortunately, I am getting different values.

For example, for the string "192.168.1.1":

  • When performing the calculation with S_un_b , I am getting the result 3232235777 (which is the correct value)
  • When simply taking the value in S_addr , I am getting the result 16885952.

My questions are:

  1. why is there a difference?

  2. Can I utilize S_addr to get the desired value?

According to the MSDN doc for in_addr :

struct in_addr {
  union {
    struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
    struct { u_short s_w1,s_w2; } S_un_w;
    u_long S_addr;
  } S_un;
};

So what you want is just the u_long member, in network order (since you want s_b1 to be the highest order byte):

unsigned int resIp = htonl(ip4addr.sin_addr.S_un.S_addr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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