实现封装一个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位