12 Linux UDP简单通信


前言 (含目录)


下面分别是服务器端和客户端的源码, 基于UDP的简单通信

/**
 * @name server.c
 * @author IYATT-yx
 * @brief 套接字UDP通信 - 服务器端
 */
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1)
    {
        perror("socket error");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(11111);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(fd, (struct sockaddr *)&server, sizeof(server)) == -1)   
    {
        perror("bind error");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in client;
    socklen_t clientLen = sizeof(client);
    char buf[1024] = {0};
    // 通信
    while (true)
    {
        // 接收
        if (recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &clientLen) == -1)
        {
            perror("recvfrom error");
            exit(EXIT_FAILURE);
        }

        char ipbuf[64];
        printf("收到来自%s:%d的数据: %s\n", inet_ntop(AF_INET, &client.sin_addr.s_addr,
                 ipbuf, sizeof(ipbuf)), ntohs(client.sin_port), buf);
        // 回复
        memset(buf, 0, sizeof(buf));
        strcpy(buf, "服务器已收到数据");
        if (sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr *)&client, sizeof(client)) == -1)
        {
            perror("sendto error");
            exit(EXIT_FAILURE);
        }
    }

    close(fd);
}
/**
 * @name client.c
 * @author IYATT-yx
 * @brief 套接字UDP通信 - 客户端端
 */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1)
    {
        perror("socket error");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(11111);
    inet_pton(AF_INET, "127.0.0.1", &server.sin_addr.s_addr);

    while (true)
    {
        // 发送数据
        printf("请输入要发送的内容:");
        char buf[1024] = {0};
        fgets(buf, sizeof(buf), stdin);
        sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr *)&server, sizeof(server));
        // 接收数据
        recvfrom(fd, buf, strlen(buf) + 1, 0, NULL, NULL);
        printf("收到服务器的消息: %s\n", buf);
    }

    close(fd);
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值