如何增加表示为一个字符串的IP地址?(How do I increment an IP addres

2019-08-17 03:39发布

我在char类型,比如CHAR IP = IP地址“192.123.34.134”我希望增加的最后一个值(134)。 有谁应该怎么办呢? 我想,我应该把它转换为整数,然后再回来,但不幸的是我不知道怎么样? :(我使用C ++。

请帮我!

谢谢,kampi

Answer 1:

您可以将IP地址从一个字符串中使用转换为整数inet_addr ,然后,操纵它后,将其转换回一个字符串inet_ntoa

见文档这些功能如何使用它们的更多信息。

这里有一个小的功能,将你想要做什么:

// NOTE: only works for IPv4.  Check out inet_pton/inet_ntop for IPv6 support.
char* increment_address(const char* address_string)
{
    // convert the input IP address to an integer
    in_addr_t address = inet_addr(address_string);

    // add one to the value (making sure to get the correct byte orders)
    address = ntohl(address);
    address += 1;
    address = htonl(address);

    // pack the address into the struct inet_ntoa expects
    struct in_addr address_struct;
    address_struct.s_addr = address;

    // convert back to a string
    return inet_ntoa(address_struct);
}

包括<arpa/inet.h>在* nix系统,或<winsock2.h>于Windows。



Answer 2:

快速/肮脏!

void increment(std::string& ip)
{
    std::string::size_type dot = ip.find_last_of('.');
    std::stringstream stream(ip.substr(dot+1));
    int part = 0;

    stream >> part;

    part++;

    stream.str(""); stream.clear();

    stream << part;

    ip.replace(dot+1, std::string::npos, stream.str());
}


Answer 3:

int a,b,c,d;
sscanf(str, "%d.%d.%d.%d", &a,&b,&c,&d);
sprintf(str, "%d.%d.%d.%d\0", a,b,c,d+1);


Answer 4:

我会写一个接受该格式的字符串的方法。
将其转换为4个整数。 增量。 (重要检查范围)
然后再转换回字符串。

如果你想要更多的财产以后长期和强大的代表IP地址的类。 然后,你保持一类控制和操纵,appropraite并在需要时转换为字符串。

#include <iostream>
#include <istream>
#include <sstream>
#include <string>
#include <stdexcept>



class MyIp
{
    struct Dot
    {};
    struct Byte
    {
        Byte(unsigned char& val)
            :m_val(val)
        {}
        unsigned char&  m_val;
    };
    friend std::istream& operator>>(std::istream& str,MyIp::Dot const& d);
    friend std::istream& operator>>(std::istream& str,MyIp::Byte const& b);
    friend std::ostream& operator<<(std::ostream& str,MyIp const& ip);
    public:
        MyIp(std::string const& ip)
        {
            std::stringstream str(ip);
            str >> Byte(ad[0]) >> Dot() >> Byte(ad[1]) >> Dot() >> Byte(ad[2]) >> Dot() >> Byte(ad[3]);
            std::string leftover;
            if (str >> leftover)
            {   throw std::runtime_error("InvalidIP: Long");
            }
        }
        void inc(int index)
        {
            if ((index >= 0) && (index <=3))
            {
                ++ad[index];
                if (ad[index] == 0)
                {
                    inc(index-1);
                }
            }
        }
    private:
        unsigned char   ad[4];
};
std::istream& operator>>(std::istream& str,MyIp::Dot const& d)
{
    char x  = str.get();
    if (x != '.')
    {   throw std::runtime_error("Invalid IP: Dot");
    }
    return str;
}
std::istream& operator>>(std::istream& str,MyIp::Byte const& b)
{
    unsigned int val;
    str >> val;
    if (!str || val > 255)
    {   throw std::runtime_error("Invalid IP: Val");
    }
    b.m_val = static_cast<unsigned char>(val);
    return str;
}
std::ostream& operator<<(std::ostream& str,MyIp const& ip)
{
    return str  << static_cast<unsigned int>(ip.ad[0])
                << "." << static_cast<unsigned int>(ip.ad[1])
                << "." << static_cast<unsigned int>(ip.ad[2])
                << "." << static_cast<unsigned int>(ip.ad[3]);
}

int main()
{
    try
    {
        std::string ip("127.0.0.1");

        MyIp    addr(ip);

        std::cout << addr << "\n";
        addr.inc(3);
        std::cout << addr << "\n";
    }
    catch(std::exception const& e)
    {
        std::cout << "What: " << e.what() << "\n";
    }
}


Answer 5:

您还可以使用最后的位置“” 并从那里取到结束转换为int,凹凸起来1,检查边界和然后将其转换为字符串,并追加到基体部分。



Answer 6:

这可能还不是很健全,但它是有趣的思考。

由于IP地址空间为32位,你可以写一个函数将IP地址转换成32位无符号整数。 然后,你可以增加或减少1或者只要你想多了,和转换回一个IP地址。 你不会担心范围检查。

在为192.123.34.134 pseduo代码你会做:

int i = (192 << 24) + (123 << 16) + (34 << 8) + 134

更一般地,为ABCD:

int i = (a << 24) + (b << 16) + (c << 8) + d

现在改变i ,只要你想尽可能多的( i++i+=10000 )和转换回:

String ip = (i >> 24) + "." + 
            ((i >> 16) mod 256) + "." + 
            ((i >> 8) mod 256) + "." + 
            (i mod 256);

请问语法 - 我不能写C ++来拯救自己。

MK



Answer 7:

本网站吃了我的标签,所以我会再试一次。 我敢肯定有一个图书馆这样做,但这应该工作(假定我的语法是不是搞砸)足以传达出的主意。

伪代码:

char[] ipAddress= "192.123.34.134";

if (ipAddress[ipAddress.Length-1] == '9')
{
    if(ipAddress[ipAddress.Length-2]=='9')
    {
        ipAddress[ipAddress.Length-1]='0';
        ipAddress[ipAddress.Length-2]='0';
        ipAddress[ipAddress.Length-3]=(char)ipAddress[ipAddress.Length-3]+1;
    }
    else
    {
        ipAddress[ipAddress.Length-2]=(char)ipAddress[ipAddress.Length-2]+1;
        ipAddress[ipAddress.Length-1]='0';
    }
}
else
{
     ipAddress[ipAddress.Length-1]=(char)ipAddress[ipAddress.Length-1]+1;
}


文章来源: How do I increment an IP address represented as a string?