Saf*_*ari 70 c++ string struct ip-address in-addr
如何转换字符串ipAddress(struct in_addr),反之亦然?以及如何打开unsigned long ipAddress?谢谢
Mil*_*lan 125
使用inet_ntop(),inet_pton()如果您需要其他方式.不要使用inet_ntoa(), inet_aton()和相似,因为它们已被弃用且不支持ipv6.
这是一个很好的指南,有很多例子.
// 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"
Run Code Online (Sandbox Code Playgroud)
我不确定我是否正确理解了这个问题。
无论如何,您是否正在寻找这个:
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;
Run Code Online (Sandbox Code Playgroud)
192 168 1 54
Run Code Online (Sandbox Code Playgroud)
我能够将字符串转换为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
Run Code Online (Sandbox Code Playgroud)
我正在使用旧的MFC代码维护项目,因此转换不赞成使用的函数调用不适用。