![](/img/trans.png)
[英]What does inet_pton do? Shouldn't I get my IP address but in decimal?
[英]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。 我的問題是:
為什么有區別?
我可以利用S_addr獲得所需的值嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.