什么是Windows XP等效的inet_pton或InetPton? [英] What is the Windows XP equivalent of inet_pton or InetPton?
问题描述
我需要确定特定字符串是否是有效的IPv4或IPv6地址文字。如果我理解正确,在POSIX系统上执行此操作的正确方法是使用 inet_pton
将其转换为网络地址结构并查看是否成功。 Windows Vista及更高版本具有 InetPton
,这基本上是相同的。但据我所知,Windows XP并未声明其中任何一种,我需要能够在XP上正确执行此操作。那么,问题是使用什么系统函数来做到这一点?
I need to determine whether a particular string is a valid IPv4 or IPv6 address literal. If I understand correctly, the correct way to do this on POSIX systems is to use inet_pton
to convert it into a network address structure and see if it succeeds. Windows Vista and later have InetPton
which does essentially the same thing. But as far as I can tell, Windows XP doesn't declare either of those, and I need to be able to do this correctly on XP. So, the question is what system function to use to do this?
最坏的情况,我可以编写一个函数自己解析它,但我更喜欢标准,因此,系统功能已经过彻底测试并能正确处理所有角落情况等等。已经很糟糕的是,微软不能像其他人一样宣布 inet_pton
,并为新的操作系统选择了 InetPton
。
Worst case, I can write a function to parse it myself, but I'd prefer a standard, system function which has therefore been thoroughly tested and properly handles all corner cases and whatnot. It's already bad enough that Microsoft couldn't just declare inet_pton
like everyone else and went with InetPton
for their newer OSes.
推荐答案
在Windows XP中,您可以使用以下功能:
In windows XP you can use these functions:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
int inet_pton(int af, const char *src, void *dst)
{
struct sockaddr_storage ss;
int size = sizeof(ss);
char src_copy[INET6_ADDRSTRLEN+1];
ZeroMemory(&ss, sizeof(ss));
/* stupid non-const API */
strncpy (src_copy, src, INET6_ADDRSTRLEN+1);
src_copy[INET6_ADDRSTRLEN] = 0;
if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
switch(af) {
case AF_INET:
*(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
return 1;
case AF_INET6:
*(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
return 1;
}
}
return 0;
}
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
{
struct sockaddr_storage ss;
unsigned long s = size;
ZeroMemory(&ss, sizeof(ss));
ss.ss_family = af;
switch(af) {
case AF_INET:
((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src;
break;
case AF_INET6:
((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src;
break;
default:
return NULL;
}
/* cannot direclty use &size because of strict aliasing rules */
return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0)?
dst : NULL;
}
就是这样。与ws2_32库链接。
That's it. Link with ws2_32 library.
这篇关于什么是Windows XP等效的inet_pton或InetPton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!