C++应用(一)使用socket创建UDP服务器端和客户端
UDP通信步骤
引用UDP通信步骤
一、UDP套接字服务端架构步骤
1. //初始化套接字环境WSAStartup
2. //初始化地址和端口
3. //创建UDP套接字socket
4. //绑定端口bind
5. //用recvfrom接收数据
6. //用sendto发送数据
7. //退出或者返回第5步继续
二、UDP客户端架构步骤
1. //初始化套接字环境WSAStartup
2. //初始化地址和端口
3. //创建UDP套接字socket
4. //用sendto发送数据
5. //用recvfrom接收数据
UDP Socket
引用UDP Socket
UDP Socket网络编程的API不多,socket()用于创建套接字,close()用于关闭套接字,sendto()用于发送数据,recvfrom()用于接收数据。
bind()顾名思义是绑定,TCP可以绑定,UDP也可以,bind用于UDP等于告诉内核:这个套接字跟网络远端的一个对子关联上了。以后就可以直接调用send()往那个标识的主机上的进程发送UDP数据报了。
而没有bind之前,只能通过sendto()接口(通过参数指定目的地)。UDP套接字recv()返回的是UDP数据报的数据部分(Payload),不包括UDP数据报首部,这是因为UDP首部的字段用于分发或者校验,不需要透传给应用程序。
每个函数含义
int socket(int domain, int type, int protocol)
- domain:指明了协议族/域,通常 AF INET, AF INET6, AF_LOCAL;
- type:套接口类型,主要 SOCK STREAM(TCP), SOCK DGRAM(UDP), SOCK_RAW(原始socket);
- protocol:一般取为0。成功时,返回一个小的非负整数值,与文件描述符类似;
- return:成功0; 失败-1;
int bind(int sockfd, const struct sockaddr* my_addr, socklen_t addrlen);
bind 功能是把一个本地协议地址赋予一个套接字,告知内核去选择该IP地址。
- sockfd: 套接字实例;
- my_addr:指向 sockaddr 结构体类型的指针;
- addrlen:表示 my_addr 结构的长度,用 sizeof 操作符获取;
- return:成功0; 失败-1;
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
- sockfd: 正在监听端口的套接口实例;
- buf:要发送的数组;
- len: 要发送的数组的字节大小;
- flags: 填0即可;
- dest_addr: 指定数据要发送到哪个主机,哪个进程;
- addrlen: 表示 dest_addr 所指向内容的长度;
- return:成功: 数据长度; 失败: -1;
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
- sockfd: 正在监听端口的套接口实例;
- buf: 要接收的数组;
- len: 要接收的数组的字节大小;
- flags: 填0即可;
- src_addr: 获取接收的数据是从哪个主机地址发来的;
- addrlen: 表示 src_addr 所指向内容的长度;
- 返回值: 成功: 数据长度; 失败: -1;
int connect(int soctfd, const struct sockaddr * addr, int addrlen);
connect 功能是用于建立与指定socket的连接,可用可不用。
- soctfd:标识一个未连接socket;
- addr:指向要连接套接字的sockaddr结构体的指针;
- addrlen:sockaddr结构体的字节长度;
-
return:成功0; 失败-1;
a. 硬错:端口号错误,服务器进程未开启,收到RST,立刻返回ECONNREFUSED;
b. 软错:IP不可达,协议ICMP,比如 no route to host,通常是发送arp请求无响应;
小工具使用
// 打印ip和port
std::printf("接收到一个连接, 其ip: %s, port: %d\n", inet_ntoa(m_RemoteAddress.sin_addr), ntohs(m_RemoteAddress.sin_port));
// 将ip转格式到sin_addr
inet_pton(AF_INET, ip, &m_RemoteAddress.sin_addr);
cpp_UDP
一、cpp_UDP客户端
#include <winsock2.h>
#include <WS2tcpip.h>
#include <iostream>
using namespace std;
//添加动态库的lib
#pragma comment(lib, "ws2_32.lib")
int main() {
SOCKET m_Socket;
SOCKADDR_IN m_RemoteAddress; //远程地址
int m_RemoteAddressLen;
// socket环境
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup error:" << GetLastError() << endl;
return false;
// socket对象
m_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (m_Socket == INVALID_SOCKET)
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return false;
// 远端地址
const char* ip = "127.0.0.1";
int port = 1000;
m_RemoteAddress.sin_family = AF_INET;
m_RemoteAddress.sin_port = htons(port);
m_RemoteAddressLen = sizeof(m_RemoteAddress);
inet_pton(AF_INET, ip, &m_RemoteAddress.sin_addr);
// 接收和发送
char recvBuf[1024] = { 0 };
char sendBuf[1024] = "Nice to meet you!";
while (1) {
int sendLen = sendto(m_Socket, sendBuf, strlen(sendBuf), 0, (sockaddr*)&m_RemoteAddress, m_RemoteAddressLen);
if (sendLen > 0) {
std::printf("发送到远程端连接, 其ip: %s, port: %d\n", inet_ntoa(m_RemoteAddress.sin_addr), ntohs(m_RemoteAddress.sin_port));
cout << "发送到远程端的信息: " << sendBuf << endl;
int recvLen = recvfrom(m_Socket, recvBuf, 1024, 0, NULL, NULL);
if (recvLen > 0) {
std::printf("接收到一个连接, 其ip: %s, port: %d\n", inet_ntoa(m_RemoteAddress.sin_addr), ntohs(m_RemoteAddress.sin_port));
cout << "接收到一个信息: " << recvBuf << endl;
closesocket(m_Socket);
WSACleanup();
return true;
}
二、cpp_UDP服务端
#include <winsock2.h>
#include <WS2tcpip.h>
#include <iostream>
using namespace std;
//添加动态库的lib
#pragma comment(lib, "ws2_32.lib")
int main() {
SOCKET m_Socket;
SOCKADDR_IN m_BindAddress; //绑定地址
SOCKADDR_IN m_RemoteAddress; //远程地址
int m_RemoteAddressLen;
// socket环境
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup error:" << GetLastError() << endl;
return false;
// socket对象
m_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (m_Socket == INVALID_SOCKET)
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return false;
// 绑定占用<ip, port>
const char* ip = "127.0.0.1";
int port = 1000;
m_BindAddress.sin_family = AF_INET;
m_BindAddress.sin_addr.S_un.S_addr = inet_addr(ip);
m_BindAddress.sin_port = htons(port);
auto ret = bind(m_Socket, (sockaddr*)&m_BindAddress, sizeof(SOCKADDR));
if (ret == SOCKET_ERROR)
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
return false;
// 接收和发送
char recvBuf[1024] = { 0 };
char sendBuf[1024] = "Nice to meet you, too!";
m_RemoteAddressLen = sizeof(m_RemoteAddress);
std::printf("已设置绑定占用的连接, 其ip: %s, port: %d\n", inet_ntoa(m_BindAddress.sin_addr), ntohs(m_BindAddress.sin_port));
while (1) {
int recvLen = recvfrom(m_Socket, recvBuf, 1024, 0, (sockaddr*)&m_RemoteAddress, &m_RemoteAddressLen);
if (recvLen > 0) {
std::printf("接收到一个连接, 其ip: %s, port: %d\n", inet_ntoa(m_RemoteAddress.sin_addr), ntohs(m_RemoteAddress.sin_port));
cout << "接收到一个信息: " << recvBuf << endl;
int sendLen = sendto(m_Socket, sendBuf, strlen(sendBuf), 0, (sockaddr*)&m_RemoteAddress, m_RemoteAddressLen);
if (sendLen > 0) {
cout << "发送到远程端的信息: " << sendBuf << endl;