簡體   English   中英

使用inet_pton()獲取IPv4地址的無符號int表示形式

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

我正在嘗試將C ++(Windows)中的IPv4地址從std::string轉換為它的unsigned int表示形式(根據this

我設法用以下代碼做到這一點:

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;

}

我得到了正確的值,但是以下幾行不太好:

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;

我希望可以不使用sin_addr S_un_b字段然后執行計算,而只是使用S_addr字段。 不幸的是,我得到了不同的價值觀。

例如,對於字符串“ 192.168.1.1”:

  • 使用S_un_b執行計算時,我得到的結果是3232235777(這是正確的值)
  • 當僅采用S_addr的值時,我得到的結果為16885952。

我的問題是:

  1. 為什么有區別?

  2. 我可以利用S_addr獲得所需的值嗎?

根據in_addrMSDN文檔

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;
};

因此,您想要的只是網絡順序中的u_long成員(因為您希望s_b1為最高順序字節):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM