muduo网路库——InetAddress

这个类的主要作用就是封装socket
在这里插入图片描述

由于博主是在windows平台下,所以用的头文件时windows.hWs2tcpip.h
linux平台下应该用sys/socket.hnetinet/in.harpa/inet.h

InetAddress.h

#pragma once

/*  linux下
* #include<arpa/inet.h> //for sockaddr
* #include <netinet/in.h>
*/
#include <string>
#include <windows.h>

//封装socket地址类型
class InetAddress
{
public:
    //接收端口号和IP地址,填充addr_
    explicit InetAddress(uint16_t port ,std::string ip = "127.0.0.1");

    explicit InetAddress(const sockaddr_in& addr):addr_(addr){}

    std::string toIP() const;
    std::string toIPPort() const;
    uint16_t toPort() const;

    const sockaddr_in* getSockAddr() const { return &addr_; }
private:
    sockaddr_in addr_;
    
};

InetAddress

#include "InetAddress.h"

#include <Ws2tcpip.h>
#include <string.h>
/*
* windows下:
* #include <WS2tcpip.h>
* linux下:
* #include <sys/socket.h>
* #include <netinet/in.h>
* #include<arpa/inet.h>
*/
//无法包含strings.h头文件 自己写了一下bzero
#define bzero(a, b)             memset(a, 0, b)

//接收端口号和IP地址,填充addr_
InetAddress::InetAddress(uint16_t port,std::string ip)
{
    bzero(&addr_,sizeof addr_);
    addr_.sin_family = AF_INET;
    //主机字节序到网络字节序
    addr_.sin_port = htons(port);
    //字符串转成整型数据
    addr_.sin_addr.s_addr = inet_addr(ip.c_str()); 
}

std::string InetAddress::toIP() const
{
    //addr_ 读取ip地址,转换成点分十进制
    char buf[64] = {0};
    inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof buf); 
    return buf;
}

std::string InetAddress::toIPPort() const
{
    //ip:port
    char buf[64] = {0};
    inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof buf); 
    uint16_t port = ntohs(addr_.sin_port);
    sprintf(buf+strlen(buf),":%u",port);
    return buf;
}

uint16_t InetAddress::toPort() const
{
    return ntohs(addr_.sin_port);
}

测试代码

#include <iostream>
int main()
{
    InetAddress addr(8000);
    std::cout << addr.toIPPort()<< std::endl;
}

测试结果:

127.0.0.1:8000

测试正常!
在这里插入图片描述

参考文献

[1] 施磊.重写moduo库.图论科技.2020.7.

猜你喜欢

转载自blog.csdn.net/shenmingxueIT/article/details/107743280