如何将字符串转换为 IP 地址,反之亦然

发布于 2024-10-24 03:16:44 字数 68 浏览 6 评论 0原文

如何转换字符串 ipAddress (struct in_addr) ,反之亦然? 如何提交未签名的长 ip 地址? 谢谢

how can I convert a string ipAddress (struct in_addr) and vice versa?
and how do I turn in unsigned long ipAddress?
thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

李白 2024-10-31 03:16:45

此示例显示如何从字符串转换为 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); 

This example shows how to convert from string to ip, and viceversa:

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); 
海未深 2024-10-31 03:16:45

这里有易于使用、线程安全的 C++ 函数,用于将 uint32_t 本机端序转换为字符串,以及将字符串转换为本机端序 uint32_t:

#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, '\0');
    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;
}

公平警告,截至撰写本文时,它们尚未经过测试。但这些功能正是我来到这个线程时所寻找的。

here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:

#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, '\0');
    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.

爱,才寂寞 2024-10-31 03:16:45

十六进制 IP 地址到字符串 IP

#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;
}

输出:10.164.0.1

Hexadecimal IP Address to String IP

#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;
}

Output:10.164.0.1

清音悠歌 2024-10-31 03:16:45

第三个 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;
}

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).

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;
}
墨洒年华 2024-10-31 03:16:45

总结:

inet_ntoa((in_addr)recvAddrStruct.sin_addr)

一步一步:

SOCKET m_viSock = socket(AF_INET, SOCK_DGRAM,0);

struct sockaddr_in recvAddrStruct;
recvAddrStruct.sin_family = AF_INET;
recvAddrStruct.sin_port = htons((unsigned short)port);
recvAddrStruct.sin_addr.s_addr = inet_addr("127.0.0.1");  // inet_addr()


  // get back in string

printf("IP : %s",    inet_ntoa((in_addr)recvAddrStruct.sin_addr));   // inet_ntoa ()
    

在此处输入图像描述

summarize :

inet_ntoa((in_addr)recvAddrStruct.sin_addr)

step by step :

SOCKET m_viSock = socket(AF_INET, SOCK_DGRAM,0);

struct sockaddr_in recvAddrStruct;
recvAddrStruct.sin_family = AF_INET;
recvAddrStruct.sin_port = htons((unsigned short)port);
recvAddrStruct.sin_addr.s_addr = inet_addr("127.0.0.1");  // inet_addr()


  // get back in string

printf("IP : %s",    inet_ntoa((in_addr)recvAddrStruct.sin_addr));   // inet_ntoa ()
    

enter image description here

江挽川 2024-10-31 03:16:45

您可以使用两个函数
在 Windows 上在 winsock2.h 中定义,在 Linux 上在 netdb.h 中定义

WSAStringToAddressA(用于将字符串转换为地址)

WSAddressToStringA(用于将地址转换为字符串)

这两个函数最好的一点是它们适用于每个地址族

WSAStringToAddressA

该函数接受五个参数

•包含您的地址的数组或 char 数组的指针

•您的地址的地址族(仅如果参数 3 为 NULL,则使用)

WSAPROTOCOL_INFO 结构提供有关您的协议的信息,如果要使用参数 2,则保留 null

•指向 sockaddr< 结构的指针/code> 其中必须存储结果地址

DWORD 类型对象的指针,其中必须存储地址的结果长度

WSAAddressToStringA

该函数还采用五个参数

• 指向必须翻译的sockaddr 结构

• 地址的字节长度

WSAPROTOCOL_INFO 结构提供有关地址协议的信息。使用NULL使函数在参数1中使用sockaddr结构的地址族。

char数组,其中字符串形式的地址具有要存储的

地址的字符串形式的长度(以字节为单位)

示例

#define _WIN32_INNT 0x601

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <ws2spi.h>

int main()
{
    WSADATA wsd;
    WSAStartup(MAKEWORD(2,2),&wsd);
    char *addr="127.0.0.1";
    sockaddr h;
    int i;
    WSAStringToAddressA(addr,AF_INET,NULL,&h,(DWORD*)&i);
    char addr2[INET_ADDRSTRLEN];
    int i2;
    WSAAddressToStringA(&h,i,NULL,addr,(DWORD*)&i2);
    std::cout<<addr2;
}

结果

127.0.0.1

You can use two functions
defined in winsock2.h on windows, in netdb.h on Linux

WSAStringToAddressA(For converting a string to an address)

WSAAddressToStringA(For converting an address to a string)

Best thing about these two functions is that they work for every address family

WSAStringToAddressA

This function takes to five arguments

•A pointer of array or array of char containing your address

•Address family of your address(Only used if argument 3 is NULL)

WSAPROTOCOL_INFO structure providing information about your protocol, leave null if you want to use argument 2

•Pointer to the structure of sockaddr in which the result address has to be stored

•Pointer of the object of type DWORD in which the result length of your address has to be stored

WSAAddressToStringA

This function also takes five arguments

•Pointer to the structure of sockaddr that has to be translated

•Byte length of your address

•Structure of WSAPROTOCOL_INFO giving information about the address's protocol. Use NULL to make the function use address family of sockaddr structure in argument 1

•Array of char in which the address in the form of string has to be stored

•Length of the string form of your address in bytes

Example

#define _WIN32_INNT 0x601

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <ws2spi.h>

int main()
{
    WSADATA wsd;
    WSAStartup(MAKEWORD(2,2),&wsd);
    char *addr="127.0.0.1";
    sockaddr h;
    int i;
    WSAStringToAddressA(addr,AF_INET,NULL,&h,(DWORD*)&i);
    char addr2[INET_ADDRSTRLEN];
    int i2;
    WSAAddressToStringA(&h,i,NULL,addr,(DWORD*)&i2);
    std::cout<<addr2;
}

Result

127.0.0.1

清风无影 2024-10-31 03:16:45

在 PowerShell 中:

[System.Net.IPAddress]::Parse("10.128.1.50").Address
[System.Net.IPAddress]::new(838959114).IPAddressToString

In PowerShell:

[System.Net.IPAddress]::Parse("10.128.1.50").Address
[System.Net.IPAddress]::new(838959114).IPAddressToString
青衫儰鉨ミ守葔 2024-10-31 03:16:44

如果您需要其他方式,请使用 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"

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.

Here is a nice guide with 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"
初懵 2024-10-31 03:16:44

我不确定我是否正确理解了这个问题。

不管怎样,你在寻找这个:

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

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;

Output:

192  168  1  54
儭儭莪哋寶赑 2024-10-31 03:16:44

我能够使用以下代码将字符串转换为 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 代码的维护项目,因此转换已弃用的函数调用不适用。

I was able to convert string to DWORD and back with this code:

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.

假面具 2024-10-31 03:16:44

inet_ntoa() 转换 in_addr 到字符串:

inet_ntoa 函数将
(Ipv4) Internet 网络地址转换
Internet 标准中的 ASCII 字符串
点分十进制格式。

inet_addr() 执行相反的工作

inet_addr 函数将一个
包含 IPv4 的字符串
点分十进制地址转换为正确的
IN_ADDR 结构的地址

PS 这是谷歌搜索“in_addr to string”的第一个结果!

inet_ntoa() converts a in_addr to string:

The inet_ntoa function converts an
(Ipv4) Internet network address into
an ASCII string in Internet standard
dotted-decimal format.

inet_addr() does the reverse job

The inet_addr function converts a
string containing an IPv4
dotted-decimal address into a proper
address for the IN_ADDR structure

PS this the first result googling "in_addr to string"!

你穿错了嫁妆 2024-10-31 03:16:44

将字符串转换为 in-addr:

in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);

将 in_addr 转换为字符串:

char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);

To convert string to in-addr:

in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);

To convert in_addr to string:

char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文