IP的int型与char*型相互转化

来源:互联网 发布:电脑连接网络错误651 编辑:程序博客网 时间:2024/05/16 18:08
<pre name="code" class="cpp">char * int2ipstr (const int ip, char *buf){sprintf (buf, "%u.%u.%u.%u",(char) * ((char *) &ip + 0),(char) * ((char *) &ip + 1),(char) * ((char *) &ip + 2), (char) * ((char *) &ip + 3));return buf;};


<pre name="code" class="cpp">uint32_t IPToValue(const string& strIP){uint32_t a[4];string IP = strIP;string strTemp;size_t pos;size_t i=3;do{pos = IP.find(".");if(pos != string::npos){strTemp = IP.substr(0,pos);a[i] = atoi(strTemp.c_str());i--;IP.erase(0,pos+1);}else{strTemp = IP;a[i] = atoi(strTemp.c_str());break;}}while(1);uint32_t nResult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0];return nResult;}


                                             
0 0