网络编程之:IP的ULONG方式字符串方式的相互转化
- // IpAndStr.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <WinSock2.h>
- #include <Windows.h>
- #include <iostream>
- #include <string>
- using namespace std;
- #pragma comment(lib, "ws2_32.lib")
- string GetIpFromULong(unsigned long uIp)
- {
- in_addr addr;
- memcpy(&addr, &uIp, sizeof(uIp));
- string strIp = inet_ntoa(addr);
- return strIp;
- }
- int main(int aargc, char* argv[])
- {
- in_addr addr1;
- unsigned long uIp = 0;
- uIp = inet_addr("127.0.0.1");
- memcpy(&addr1, &uIp, sizeof(uIp));
- //cout << "strip = " << inet_ntoa(addr1) << endl;
- string strIp = GetIpFromULong(uIp);
- cout << "cur ip = " << strIp.c_str() << endl;
- /* struct in_addr addr1,addr2;
- unsigned long l1,l2;
- l1 = inet_addr("192.168.0.74");
- l2 = inet_addr("211.100.21.179");
- memcpy(&addr1, &l1, 4);
- memcpy(&addr2, &l2, 4);
- printf("%s : %s\n", inet_ntoa(addr1), inet_ntoa(addr2)); //注意这一句的运行结果
- printf("%s\n", inet_ntoa(addr1));
- printf("%s\n", inet_ntoa(addr2));*/
- return 0;
- }