Linux网络编程()sockaddr操作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_;
};
#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;
}
上一篇:基于时频变换的脑波信号(EEG)处理方法


下一篇:UDP详解