如何将字符串转换为IP地址,反之亦然
答
使用inet_ntop()
和inet_pton()
如果您需要其他方法。不要使用inet_ntoa(), inet_aton()
和类似的,因为它们已被弃用,不支持ipv6。
这里有一个不错的guide有不少例子。
// IPv4 demo of inet_ntop() and inet_pton()
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));
// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str); // prints "192.0.2.33"
答
inet_ntoa()
转换一个in_addr
字符串:
的INET_NTOA功能的 (IPv4)Internet上的网络地址转换成 在Internet标准 点分十进制格式的ASCII字符串。
inet_addr()
做相反的作业
的inet_addr函数转换包含IPv4 点分十进制地址转换成一个适当的 地址IN_ADDR结构
PS一个 字符串这个首先搜索结果“in_addr to string”!
答
我不知道我是否正确理解了这个问题。
反正你找这样的:
std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << " " << b << " " << c << " "<< d;
192 168 1 54
答
要字符串转换为-地址:
in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);
要组in_addr转换成字符串:
char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);
答
我可以将字符串转换为DWORD和背部与此代码:
char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]
struct in_addr paddr;
paddr.S_un.S_addr = ip;
char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd
我在旧MFC代码维护项目的工作,所以不推荐使用转换函数的调用是不适用的。
答
这个例子说明了如何从字符串转换为IP,反之亦然:
struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));
// now get it back
sprintf(ip_saver, "%s", sa.sin_addr));
// prints "192.0.2.10"
printf("%s\n", ip_saver);
我应该怎么做才能在Windows下使用它们? 我应该包括什么? – Safari 2011-03-16 16:41:27
如果在Windows Vista和更高版本上使用winsock,则使用InetNtop和InetPton。头文件Ws2tcpip.h。小技巧是看msdn上的例子。 – Milan 2011-03-16 16:46:32
我使用Windows XP。 – Safari 2011-03-16 16:55:31