sockaddr操作C++封装

Posted 奇妙之二进制

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sockaddr操作C++封装相关的知识,希望对你有一定的参考价值。

代码严格遵循Google C++风格。

net/InetAddress.h

#ifndef _INET_ADDRESS_H_
#define _INET_ADDRESS_H_

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#include <string>

class Ipv4Address {
 public:
  Ipv4Address();
  Ipv4Address(std::string ip, uint16_t port);
  void SetAddr(std::string ip, uint16_t port);
  std::string GetIp();
  uint16_t GetPort();
  struct sockaddr* GetAddr();

 private:
  std::string ip_;
  uint16_t port_;
  struct sockaddr_in socket_addr_;
};

InetAddress.cpp

#include "net/InetAddress.h"

Ipv4Address::Ipv4Address() {}

Ipv4Address::Ipv4Address(std::string ip, uint16_t port) : ip_(ip), port_(port) {
  socket_addr_.sin_family = AF_INET;
  socket_addr_.sin_addr.s_addr = inet_addr(ip.c_str());
  socket_addr_.sin_port = htons(port);
}

void Ipv4Address::SetAddr(std::string ip, uint16_t port) {
  ip_ = ip;
  port_ = port;
  socket_addr_.sin_family = AF_INET;
  socket_addr_.sin_addr.s_addr = inet_addr(ip.c_str());
  socket_addr_.sin_port = htons(port);
}

std::string Ipv4Address::GetIp() { return ip_; }

uint16_t Ipv4Address::GetPort() { return port_; }

struct sockaddr* Ipv4Address::GetAddr() {
  return (struct sockaddr*)&socket_addr_;
}

测试代码:

#include "net/InetAddress.h"

#include <iostream>

int main() {
        Ipv4Address address("192.168.1.1",4096);
        std::cout << "ip = " << address.GetIp() << ",potr = " << address.GetPort() << std::endl;
        Ipv4Address address1;
        address1.SetAddr("192.168.1.1",4096);
        std::cout << "ip = " << address1.GetIp() << ",potr = " << address.GetPort() << std::endl;
}

以上是关于sockaddr操作C++封装的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

C++三大特性(继承封装多态)

这些 C++ 代码片段有啥作用?

如何从 ip 地址或 sockaddr_in 结构 (C++/WinAPI) 中获取主机名?

有趣的 C++ 代码片段,有啥解释吗? [复制]