UDP介绍
UDP — ⽤户数据报协议,是⼀个⽆连接的简单的⾯向数据报的运输层协 议。UDP不提供可靠性,它只是把应⽤程序传给IP层的数据报发送出去,但是并不能保证它们能到达⽬的地。由于UDP在传输数据报前不⽤在客户和服 务器之间建⽴⼀个连接,且没有超时重发等机制,故⽽传输速度很快。
UDP是⼀种⾯向⽆连接的协议,每个数据报都是⼀个独⽴的信息,包括完整 的源地址或⽬的地址,它在⽹络上以任何可能的路径传往⽬的地,因此能否 到达⽬的地,到达⽬的地的时间以及内容的正确性都是不能被保证的。
UDP通信这里采用socket通信方法,其方法已经在【TCP通信】原理详解与编程实现(二)说明,这里不再赘述,直接给出代码。
1 send端
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <error.h>
#include <stdlib.h>
#include <arpa/inet.h>
using namespace std;
int main(int argc, char *argv[])
{
struct sockaddr_in s_addr;//结构体
int sock;
int addr_len;//获取结构长度
int len;
char buff[128];
int yes;
if (argc != 2)
{
printf("Please input %s IP\n",argv[1]);
}
if(-1 == (sock = socket(AF_INET, SOCK_DGRAM, 0))