UDP模拟实现

该博客介绍了如何封装一个UDPSocket类,并通过实例展示了UDP服务端和客户端的程序编写,进而实现了本地UDP客户端与阿里云服务器的简单通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现封装一个UDPSocket类

/*实现封装一个UDPSocket类,向外提供方便的套接字操作接口
 * bool Socket()    创建套接字
 * bool Bind(std::string &ip,uint16_t port)
 * bool Recv(std::string &buf,std::string &ip,uint16_t port)
 * bool Send(std::string &buf,std::string &ip,uint16_t port)
 * bool Close()*/
#include <iostream>
#include <string>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define  CHECK_RET(q) if((q)==false){return -1;}
class UDPSocket
{
   
public:
  UDPSocket():_sockfd(-1)
  {
   }
  ~UDPSocket()
  {
   
    close(_sockfd);
  }
  bool Socket()
  {
   
    //int socket(int domain, int type, int protocol);
    _sockfd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if(_sockfd<0)
    {
   
      perror("socket error");
      return false;
    }
    return true;
  }
  bool Bind(std::string &ip,uint16_t port)
  {
   
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    //因为端口和地址都是要在网络上传输的,因此需要字节序转换
    //uint32_t htonl(uint32_t hostlong);
    //将32位的数据从主机字节序转换为网络字节序
    //uint16_t htons(uint16_t hostshort);
    //将16位的数据从主机字节序转换为网络字节序
    //uint32_t ntohl(uint32_t netlong);
    //将32位的数据从网络字节序转换为主机字节序
    //uint16_t ntohs(uint16_t netshort);
    //将16位的数据从网络字节序转换为主机字节序
    addr.sin_port=htons(port);//port是两个字节的数据16位
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值