网络编程之:IP的ULONG方式字符串方式的相互转化

 

  1. // IpAndStr.cpp : Defines the entry point for the console application.   
  2. //   
  3.   
  4. #include "stdafx.h"   
  5. #include <WinSock2.h>   
  6. #include <Windows.h>   
  7. #include <iostream>   
  8. #include <string>   
  9. using namespace std;   
  10.   
  11. #pragma comment(lib, "ws2_32.lib")   
  12.   
  13. string GetIpFromULong(unsigned long uIp)   
  14. {   
  15.     in_addr addr;   
  16.   
  17.     memcpy(&addr, &uIp, sizeof(uIp));   
  18.   
  19.     string strIp = inet_ntoa(addr);   
  20.   
  21.     return strIp;   
  22. }   
  23.   
  24.   
  25. int main(int aargc, char* argv[])   
  26. {   
  27.     in_addr addr1;   
  28.     unsigned long uIp = 0;   
  29.   
  30.     uIp = inet_addr("127.0.0.1");   
  31.     memcpy(&addr1, &uIp, sizeof(uIp));   
  32.   
  33.     //cout << "strip = " << inet_ntoa(addr1) << endl;   
  34.   
  35.     string strIp = GetIpFromULong(uIp);   
  36.   
  37.     cout << "cur ip = " << strIp.c_str() << endl;   
  38.   
  39. /*  struct in_addr addr1,addr2;  
  40.     unsigned long l1,l2;  
  41.  
  42.     l1 = inet_addr("192.168.0.74");  
  43.     l2 = inet_addr("211.100.21.179");  
  44.     memcpy(&addr1, &l1, 4);  
  45.     memcpy(&addr2, &l2, 4);  
  46.     printf("%s : %s\n", inet_ntoa(addr1), inet_ntoa(addr2)); //注意这一句的运行结果  
  47.     printf("%s\n", inet_ntoa(addr1));  
  48.     printf("%s\n", inet_ntoa(addr2));*/  
  49.   
  50.     return 0;   
  51. }  
posted on 2010-07-22 11:41  kangwang1988  阅读(2833)  评论(0编辑  收藏  举报