嵌入式系统学习Day30(udp)

网络编程之之UDR用户数据报

1、特性:无链接不可靠大数据

2、框架:C/S模式

server : socket( ===>bind(===>recvfrom(===>close(

client : socket( ===>bind(===>sendto( ===>close0

注意:socket()的参数需要调整。

socket(PF_INET,SOCK_DGRAM,0);

bind()客户端是可选的,服务器端是比选的。

发送接收函数:

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,

const struct sockaddr *dest_addr, socklen_t addrlen);

功能:用于UDP协议中向对方发送数据。

参数:sockfd本地的套接字id

buff本地的数据存储,一般是要发送的数据。

len要发送的数据长度

flags要发送数据方式,0表示阻塞发送。

dest_addr: 必选,表示要发送到的目标主机信息结构体。

addrlen:目标地址长度。

返回值:成功发送的数据长度

cs 复制代码
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h> /* See NOTES */
#include <unistd.h>
#include <time.h>

typedef struct sockaddr * (SA);
int main(int argc, char **argv)
{
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (-1 == sockfd)
  {
    perror("socket");
    return 1;
  }

  // man 7 ip
  struct sockaddr_in ser, cli;
  ser.sin_family = AF_INET;
  // host to net short
  ser.sin_port = htons(50000);
  ser.sin_addr.s_addr = inet_addr("192.168.14.128");
  int ret = bind(sockfd,(SA) &ser, sizeof(ser));
  if (-1 == ret)
  {
    perror("bind");
    return 1;
  }
  time_t tm;
  socklen_t len = sizeof(cli);
  while (1)
  {
    char buf[512] = {0};
    time(&tm);
    recvfrom(sockfd, buf, sizeof(buf), 0, (SA)&cli, &len);
    sprintf(buf,"%s %s",buf,ctime(&tm));
    sendto(sockfd,buf,strlen(buf),0,(SA)&cli,len);
  }

  return 0;
}
cs 复制代码
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h> /* See NOTES */
#include <time.h>
#include <unistd.h>
typedef struct sockaddr * (SA);
int main(int argc, char **argv)
{
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (-1 == sockfd)
  {
    perror("socket");
    return 1;
  }
  // man 7 ip
  struct sockaddr_in ser;
  ser.sin_family = AF_INET;
  // host to net short
  ser.sin_port = htons(50000);
  ser.sin_addr.s_addr = inet_addr("192.168.14.128");

  int i = 10;
  while (i--)
  {
    char buf[512]="hello,this udp test";
    sendto(sockfd,buf,strlen(buf),0,(SA)&ser,sizeof(ser));
    bzero(buf,sizeof(buf));
    recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
    printf("from ser:%s\n",buf);
    sleep(1);
  }
  close(sockfd);

  return 0;
}
相关推荐
汤愈韬26 分钟前
ACL概述、ACL原理、基本ACL应用及配置
网络·网络协议·网络安全
微露清风35 分钟前
系统性学习Linux-第二讲-基础开发工具
linux·运维·学习
阳光九叶草LXGZXJ1 小时前
达梦数据库-学习-48-DmDrs控制台命令(同步之Manager、CPT模块)
linux·运维·数据库·sql·学习
biuyyyxxx2 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
丝斯20113 小时前
AI学习笔记整理(66)——多模态大模型MOE-LLAVA
人工智能·笔记·学习
军军君014 小时前
Three.js基础功能学习十三:太阳系实例上
前端·javascript·vue.js·学习·3d·前端框架·three
bylander4 小时前
【AI学习】TM Forum《Autonomous Networks Implementation Guide》快速理解
人工智能·学习·智能体·自动驾驶网络
xxxmine5 小时前
redis学习
数据库·redis·学习
Yff_world6 小时前
网络通信模型
学习·网络安全
haluhalu.7 小时前
Linux网络编程------网络基础
网络·网络协议