Linux程序设计之UDP通信

  • Post author:
  • Post category:linux


1.UDP通信是不可靠的、无连接的通信,客户端只需要服务器端的地址信息即可与之进行通信。UDP通信的基本流程如下:

2.利用UDP实现服务器端与客户端的通信如下:

/*UDP通信*/
//服务端

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


int main()
{
    //1.创建套接字2
    int fd = socket(PF_INET,SOCK_DGRAM,0);
    if(fd == -1)
    {
        perror("socket");
        exit(-1);
    }

    //2.绑定
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    saddr.sin_addr.s_addr = INADDR_ANY;
    int len = sizeof(saddr);
    int ret = bind(fd,(struct sockaddr*)&saddr,len);

    //3.通信
    while(1)
    {
        //接受数据
        char buf[128];
        char bufIp[16];

        struct sockaddr_in cliaddr;
        len = sizeof(cliaddr);

        int num = recvfrom(fd,buf,sizeof(buf),0,(struct sockaddr*)&cliaddr,&len);
        printf("client IP :%s, Port : %d\n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,bufIp,sizeof(bufIp)),
        ntohs(cliaddr.sin_port));

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

        //发送数据
        sendto(fd,buf,strlen(buf) + 1,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
    }
    
    close(fd);
    return 0;
}
/*UDP通信*/
//客户端

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


int main()
{
    //1.创建套接字2
    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,"127.0.0.1",&saddr.sin_addr.s_addr);

    int num = 0;

    //2.通信
    while(1)
    {
        char sendBuf[128];
        sprintf(sendBuf,"hello,i am clien %d\n",num++);

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


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

       printf("server data : %s\n",sendBuf);

       sleep(1);
    }
    
    close(fd);
    return 0;
}

3.运行结果;

4.总结:UDP通信比TCP通信更加的简单。UDP通信的特点是:无连接、不可靠、面向报文的、支持一对一,一对多,多对一,多对多的通信等等。



版权声明:本文为qq_43213240原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。