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.
全部评论

相关推荐

04-16 10:27
已编辑
美团_Saas_后端开发
今天周一休息,突发奇想写一篇阶段总结。如题,我已经去了一个和Java彻底毫无关联的行业。曾经我以为自己能在计算机行业发光发热,拿到美团offer那会感觉自己天都亮了。没想到刚入行一年多就当了逃兵。从最开始的热爱到现在一看到代码就厌恶,不知道自己经历了什么。所以我去干什么了?答案是:在成都当了租房销售。上班那会压力大了就念叨着去干租房中介,但是一直下不去这个决心,想着自己学了四年多的计算机知识,终究还是不甘心。终于在某一天准备八股文的时候,看着无数篇和工作内容关系不大的理论知识,那一刻下定决心,决定尝试一下销售行业,也算是给自己一个交代。后面阴差阳错的投了成都自如去当租房管家,没想到面试很顺利,在当天一百多个面试的人里面,我成为了为数不多通过的几个幸运儿之一。目前已经培训通过,正式入职,也开了单,有压力但是每天过得很开心,真心喜欢那种和人交流的感觉,哪怕是最后没有选择找我租房。说这些也是想告诉那些大三,大四正在找Java实习而焦虑的同学:你们现在还年轻,选择很多,容错率也很高,可以尽情去尝试自己喜欢的行业和工作。不用因为某一次的面试没通过或者简历石沉大海而焦虑,更不用因为身边人都在挤编程的独木桥就强迫自己跟风。也算是自己的碎碎念吧,也希望自己能在新的领域取得一点小成就。也祝牛油工作顺利!
沉淀小子:干啥都不丢人啊,生存是必须要的,销售很考验一个人综合素质能力的,好的销售人脉和资源可不比写字楼的白领差啊
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务