Re: [問題] 計算network的範圍

看板C_and_CPP (C/C++)作者 (raison detre)時間13年前 (2013/04/19 12:40), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串2/2 (看更多)
以下是我想出來的程式碼 mask 24-32之間的計算都正常 可是 mask小於24的時候 第三個區間的值都不會跳 (192.168.0.255 下一個應該是 192.168.1.0 但實際上又回到 192.168.0.0) 推測應該是big endian 與 little endian的問題 但想不到比較好的做法 可以請大家給點建議嗎 我的作業系統是 linux MaskCaculator::MaskCaculator(const std::string& ip, unsigned int mask) { TRACE_SHOW(true); if(mask<=0 || mask >32) throw FRAME_EXPCEPTION_1("over the mask range"); //unsigned int _mask = inet_addr("255.255.255.255"); unsigned int _mask = 0xffffffff; _mask = htonl(_mask << (32-mask)); unsigned int _ip = inet_addr(ip.c_str()); unsigned int _subnet = _ip & _mask; int _count = pow(2, (32-mask)); for(int i=0; i<_count; i++) { _subnet += htonl(1); m_arrIp.push_back(ToIPString(_subnet)); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.220.71.34

04/19 13:43, , 2F
迴圈裡用到 +=, 只會正確作用在 host representation.
04/19 13:43, 2F
文章代碼(AID): #1HSCgkSF (C_and_CPP)
文章代碼(AID): #1HSCgkSF (C_and_CPP)