LINUX C UDP协议

3 篇文章 0 订阅

LINUX C UDP协议

简介

UDP协议是面向无连接的协议,一般用于一些实时性比较强的或正确率要求不高的通信中。

流程

上一节当中讲了linux下socket TCP编程,有了TCP的基础,UDP就好理解多了。

接收端

  1. 创建socket
  2. 绑定ip和端口
  3. 等待接收
    使用recvfrom函数

    /* Read N bytes into BUF through socket FD.
       If ADDR is not NULL, fill in *ADDR_LEN bytes of it with tha address of
       the sender, and store the actual size of the address in *ADDR_LEN.
       Returns the number of bytes read or -1 for errors.
    
       This function is a cancellation point and therefore not marked with
       __THROW.  */
    extern ssize_t recvfrom (int __fd, void * __buf, size_t __n,
                 int __flags, __SOCKADDR_ARG __addr,
                 socklen_t * __addr_len);
    
  4. close(fd) 关闭SOCKET

 发送端

  1. 创建socket
  2. 发送
    使用sendto()函数

    /* Send N bytes of BUF on socket FD to peer at address ADDR (which is
       ADDR_LEN bytes long).  Returns the number sent, or -1 for errors.
    
       This function is a cancellation point and therefore not marked with
       __THROW.  */
    extern ssize_t sendto (int __fd, const void *__buf, size_t __n,
                   int __flags, __CONST_SOCKADDR_ARG __addr,
                   socklen_t __addr_len);
    
  3. close(fd) 关闭SOCKET

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 C 语言在 Linux 中使用 UDP 协议接收结构体的示例代码: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 12345 #define BUF_SIZE 1024 struct my_struct { int a; char b[10]; double c; }; int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in server_addr; struct sockaddr_in client_addr; socklen_t client_addr_len; ssize_t recv_len; struct my_struct recv_struct; // 创建套接字 sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket"); exit(EXIT_FAILURE); } // 绑定套接字 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(PORT); if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("bind"); close(sockfd); exit(EXIT_FAILURE); } while (1) { // 接收数据 client_addr_len = sizeof(client_addr); recv_len = recvfrom(sockfd, &recv_struct, sizeof(recv_struct), 0, (struct sockaddr *)&client_addr, &client_addr_len); if (recv_len < 0) { perror("recvfrom"); close(sockfd); exit(EXIT_FAILURE); } // 打印接收到的结构体 printf("Received struct: a = %d, b = %s, c = %f\n", recv_struct.a, recv_struct.b, recv_struct.c); } close(sockfd); return 0; } ``` 上面的代码创建了一个 UDP 套接字,并绑定到本地的 PORT 端口,然后不断接收数据并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值