Linux C/C++UDP通信实现

35 篇文章 0 订阅
35 篇文章 0 订阅


一、UDP通信流程

在这里插入图片描述

二、代码实现

1.服务器

代码如下(示例):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

int main()
{
    // 1.创建一个通信的socket
    int fd = socket(PF_INET, SOCK_DGRAM, 0);

    if (fd == -1)
    {
        perror("socket");
        exit(-1);
    }

    // 2.绑定
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9999);
    addr.sin_addr.s_addr = INADDR_ANY;

    int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if (ret == -1)
    {
        perror("bind");
        exit(-1);
    }

    // 3.通信
    while (1)
    {
        char buf[128];
        char ipbuf[16];

        struct sockaddr_in caddr;
        int len = sizeof(caddr);

        //接受数据
        int num = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&caddr, &len);

        printf("client ip:%s,port :%d\n",
            inet_ntop(AF_INET, &caddr.sin_addr.s_addr, ipbuf, sizeof(ipbuf)),
            ntohs(caddr.sin_port));

        printf("client say:%s\n", buf);

        //发送数据
        sendto(fd, buf, strlen(buf) + 1,0,(struct sockaddr*)&caddr,sizeof(caddr));
    }

    close(fd);

    return 0;
}

2.客户端

代码如下(示例):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

int main()
{
    // 1.创建一个通信的socket
    int fd = socket(PF_INET, SOCK_DGRAM, 0);

    if (fd == -1)
    {
        perror("socket");
        exit(-1);
    }

    //服务器地址信息
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    inet_pton(AF_INET, "182.61.11.197", &saddr.sin_addr.s_addr);

    int num = 0;
    // 3.通信
    while (1)
    {
        char buf[128];
        sprintf(buf, "hello ,i am client %d\n", num++);

        //发送数据
        sendto(fd, buf, strlen(buf) + 1,0,(struct sockaddr*)&saddr,sizeof(saddr));

        //接受数据
        int num = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);

        printf("server say:%s\n", buf);

        sleep(1);
    }

    close(fd);

    return 0;
}


  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值