ZBLOG

如何把ipv4 从str转成unsigned int

在C++中,可以使用标准库中的函数将IPv4地址从字符串(std::stringconst char*)转换为无符号整型(unsigned int)。一种常用的方法是利用 inet_pton 函数,或者通过手动解析字符串。以下是两种方法的示例:

方法一:使用 inet_pton

#include <iostream>
#include <arpa/inet.h>

unsigned int ipv4ToUnsignedInt(const std::string& ipv4) {
    struct in_addr addr;
    if (inet_pton(AF_INET, ipv4.c_str(), &addr) != 1) {
        throw std::runtime_error("Invalid IPv4 address");
    }
    return ntohl(addr.s_addr); // 转换为主机字节序
}

int main() {
    std::string ipv4 = "192.168.1.1";
    try {
        unsigned int result = ipv4ToUnsignedInt(ipv4);
        std::cout << "Unsigned int: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}

方法二:手动解析

#include <iostream>
#include <sstream>
#include <vector>

unsigned int ipv4ToUnsignedInt(const std::string& ipv4) {
    std::istringstream iss(ipv4);
    std::string octet;
    unsigned int result = 0;
    
    for (int i = 0; i < 4; ++i) {
        if (!std::getline(iss, octet, '.')) {
            throw std::runtime_error("Invalid IPv4 address");
        }
        result <<= 8; // 左移8位,为下一个八位组腾出空间
        result |= static_cast<unsigned int>(std::stoi(octet)); // 合并当前八位组
    }

    return result;
}

int main() {
    std::string ipv4 = "192.168.1.1";
    try {
        unsigned int result = ipv4ToUnsignedInt(ipv4);
        std::cout << "Unsigned int: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    
    return 0;
}

注意事项:

  • 使用 inet_pton 时,确保包含 <arpa/inet.h> 和链接到正确的网络库。
  • 手动解析时,请处理异常和错误情况,例如地址格式不正确。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=6932

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?