作為練習,自己編了一個:
#include "stdafx.h"<br />#include <iostream><br />#include <string><br />//#include <windows.h><br />using namespace std; </p><p>int IPToValue(const string& strIP)<br />{<br />//IP轉化為數值<br />//沒有格式檢查<br />//傳回值就是結果</p><p>int a[4];<br />string IP = strIP;<br />string strTemp;<br />size_t pos;<br />size_t i=3;</p><p>do<br />{<br />pos = IP.find("."); </p><p>if(pos != string::npos)<br />{<br />strTemp = IP.substr(0,pos);<br />a[i] = atoi(strTemp.c_str());<br />i--;<br />IP.erase(0,pos+1);<br />}<br />else<br />{<br />strTemp = IP;<br />a[i] = atoi(strTemp.c_str());<br />break;<br />}</p><p>}while(1);</p><p>int nResult = (a[3]<<24) + (a[2]<<16)+ (a[1]<<8) + a[0];<br />return nResult;<br />}</p><p>string ValueToIP(const int& nValue)<br />{<br />//數值轉化為IP<br />//沒有格式檢查<br />//傳回值就是結果</p><p>char strTemp[20];<br />sprintf( strTemp,"%d.%d.%d.%d",<br />(nValue&0xff000000)>>24,<br />(nValue&0x00ff0000)>>16,<br />(nValue&0x0000ff00)>>8,<br />(nValue&0x000000ff) );</p><p>return string(strTemp);<br />}</p><p>int main(void)<br />{<br />//對於218.92.189.40轉化後-631456472<br />//cout<<hex<<-631456472 <<endl;//輸出da5cbd28</p><p>string strIP= "218.92.189.40";<br />cout<<dec<<IPToValue(strIP)<<endl;<br />//cout<<hex<<IPToValue(strIP)<<endl;<br />cout<<ValueToIP(-631456472)<<endl;</p><p>//IP為:218.92.176.82轉化後 -631459758<br />strIP= "218.92.176.82";<br />cout<<dec<<IPToValue(strIP)<<endl;<br />//cout<<hex<<IPToValue(strIP)<<endl;<br />cout<<ValueToIP(-631459758)<<endl;</p><p>return 0 ;<br />}
也可以使用現成的win socket函數,以下代碼使用vc6.0通過:
#include "stdafx.h"<br />#include <iostream><br />#include <winsock2.h> </p><p>#pragma comment(lib,"ws2_32.lib")<br />using namespace std; </p><p>int main(void)<br />{<br />cout<<(int)htonl(inet_addr("218.92.189.40"))<<endl;//輸出-631456472</p><p>struct in_addr addr;<br />addr.S_un.S_addr = ntohl(-631456472);<br />cout<<inet_ntoa( addr )<<endl;//輸出218.92.189.40</p><p>return 0 ;<br />}