嵌入式系统学习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;
}
相关推荐
是隼人5 小时前
buuctf-pwn xdctf2015_pwn200题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
大衛說5 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
吃好睡好便好6 小时前
查找函数的使用
学习·算法·matlab·生活·查找函数
学运维的Kysan6 小时前
暑假运维学习打卡第二十九天8.29
学习
zbyyd7 小时前
Linux 进程间通信学习笔记
linux·笔记·学习
一条破秋裤7 小时前
02_软件安装与新建工程
学习
来了就未晚7 小时前
Python基础 学习代码存储与命名规范
开发语言·python·学习
GHL2842710907 小时前
用codex做一个简单技能学习
学习·ai
西西弗Sisyphus9 小时前
模型训练 不同批次大小与学习率下的训练损失对比(2)
学习·batchsize·lr·learning rate
软件开发技术深度爱好者9 小时前
在线学习实践 TypeScript 的官方Playground(演练场)使用介绍
javascript·学习·typescript