C++ 如何将字符串转换为 IP 地址,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5328070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to IP address and vice versa
提问by Safari
how can I convert a string ipAddress (struct in_addr) and vice versa? and how do I turn in unsigned long ipAddress? thanks
如何转换字符串 ipAddress (struct in_addr),反之亦然?以及如何上交无符号长 ipAddress?谢谢
回答by Milan
Use inet_ntop()
and inet_pton()
if you need it other way around. Do not use inet_ntoa(), inet_aton()
and similar as they are deprecated and don't support ipv6.
使用inet_ntop()
,inet_pton()
如果您需要其他方式。不要使用inet_ntoa(), inet_aton()
和类似,因为它们已被弃用且不支持 ipv6。
Here is a nice guidewith quite a few examples.
这是一个很好的指南,里面有很多例子。
// 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"
回答by Nawaz
I'm not sure if I understood the question properly.
我不确定我是否正确理解了这个问题。
Anyway, are you looking for this:
无论如何,您是否正在寻找这个:
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
回答by Zac
I was able to convert string to DWORD and back with this code:
我能够将字符串转换为 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
I am working in a maintenance project of old MFC code, so converting deprecated functions calls is not applicable.
我在旧 MFC 代码的维护项目中工作,因此转换已弃用的函数调用不适用。
回答by Krit
To convert string to in-addr:
要将字符串转换为 in-addr:
in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);
To convert in_addr to string:
要将 in_addr 转换为字符串:
char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);
回答by CharlesB
inet_ntoa()
converts a in_addr
to string:
inet_ntoa()
将 a 转换in_addr
为字符串:
The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.
inet_ntoa 函数将 (Ipv4) Internet 网络地址转换为 Internet 标准点分十进制格式的 ASCII 字符串。
inet_addr()
does the reverse job
inet_addr()
做相反的工作
The inet_addr function converts a string containing an IPv4 dotted-decimal address into a proper address for the IN_ADDR structure
inet_addr 函数将包含 IPv4 点分十进制地址的字符串转换为 IN_ADDR 结构的正确地址
PS this the first result googling "in_addr to string"!
PS这是谷歌搜索“in_addr to string”的第一个结果!
回答by William Cuervo
This example shows how to convert from string to ip, and viceversa:
此示例显示如何将字符串转换为 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);
回答by Sourabh Bhardwaj
The third inet_pton
parameter is a pointer to an in_addr
structure. After a successful inet_pton
call, the in_addr
structure will be populated with the address information. The structure's S_addr
field contains the IP address in network byte order (reverse order).
第三个inet_pton
参数是指向in_addr
结构的指针。成功inet_pton
调用后,该in_addr
结构将填充地址信息。该结构的S_addr
字段包含网络字节顺序(逆序)中的 IP 地址。
Example :
#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
int result;
uint32_t IPv4Identifier = 0;
struct in_addr addr;
// store this IP address in sa:
result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
}
else if (result == 0) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
}
else {
IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
}
return IPv4Identifier;
}
回答by hanshenrik
here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:
这是将 uint32_t native-endian 转换为 string,并将 string 转换为 native-endian uint32_t 的易于使用、线程安全的 c++ 函数:
#include <arpa/inet.h> // inet_ntop & inet_pton
#include <string.h> // strerror_r
#include <arpa/inet.h> // ntohl & htonl
using namespace std; // im lazy
string ipv4_int_to_string(uint32_t in, bool *const success = nullptr)
{
string ret(INET_ADDRSTRLEN, '#include <iostream>
#include <sstream>
using namespace std;
int main()
{
uint32_t ip = 0x0AA40001;
string ip_str="";
int temp = 0;
for (int i = 0; i < 8; i++){
if (i % 2 == 0)
{
temp += ip & 15;
ip = ip >> 4;
}
else
{
stringstream ss;
temp += (ip & 15) * 16;
ip = ip >> 4;
ss << temp;
ip_str = ss.str()+"." + ip_str;
temp = 0;
}
}
ip_str.pop_back();
cout << ip_str;
}
');
in = htonl(in);
const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size()));
if (success)
{
*success = _success;
}
if (_success)
{
ret.pop_back(); // remove null-terminator required by inet_ntop
}
else if (!success)
{
char buf[200] = {0};
strerror_r(errno, buf, sizeof(buf));
throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf));
}
return ret;
}
// return is native-endian
// when an error occurs: if success ptr is given, it's set to false, otherwise a std::runtime_error is thrown.
uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr)
{
uint32_t ret;
const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret));
ret = ntohl(ret);
if (success)
{
*success = _success;
}
else if (!_success)
{
char buf[200] = {0};
strerror_r(errno, buf, sizeof(buf));
throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf));
}
return ret;
}
fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.
公平的警告,在撰写本文时,它们未经测试。但是当我来到这个线程时,这些功能正是我正在寻找的。
回答by Wang Aoyu
Hexadecimal IP Address to String IP
十六进制IP地址转字符串IP
##代码##Output:10.164.0.1
输出:10.164.0.1