五步
1.创建套接字 — socket
2.为套接字绑定地址信息 — bind
3.接收数据 — recvfrom
4.发送数据 — sendto
5.关闭套接字 — close
头文件:
#pragma once
#include <iostream>
#include <string>
#include <stdio.h> //perror
#include <sys/socket.h> //socket, bind, recvfrom, sendto
#include <unistd.h> //close
#include <netinet/in.h> //inet_addr
#include <arpa/inet.h> //htons
#include <stdlib.h>
using std::cout;
using std::endl;
using std::string;
using std::cin;
class UdpSocket {
public:
// 构造函数初始化
UdpSocket() {
_sock = -1;
}
// 创建套接字
bool Socket() {
_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (_sock < 0) {
perror("socket error");
return false;
}
return true;
}
// 为套接字绑定地址信息
bool Bind(const string& ip, const uint16_t port) {
struct sockaddr_in addr;
addr.sin_family = AF_INET; //IPV4协议
addr.sin_port = htons(port); //端口
addr<