C语言UDP通信

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C语言UDP通信

阿宁(xin)。   2022-06-19 我要评论

UDP通信

UDP是一种无连接的尽最大努力交付的不可靠连接,通信之前无需先建立连接,自然而然,通信之后也就无需再释放连接。

通信的套接字

UDP所采用的通信接口与前面讲过的TCP通信接口相同,只是没有建立连接这一步。

socket()用来创建套接字,使用 udp 协议时,选择数据报服务 SOCK_DGRAM。sendto()用来发送数据,由于 UDP 是无连接的,每次发送数据都需要指定对端的地址(IP 和端口)。recvfrom()接收数据,每次都需要传给该方法一个地址结构来存放发送端的地址。

recvfrom()可以接收所有客户端发送给当前应用程序的数据,并不是只能接收某一个客户端的数据

通信流程

通信过程

客户端

#include <stdio.h>

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    assert( sockfd != -1 );

    struct sockaddr_in saddr;
    memset(&saddr,0,sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6000);
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    while( 1 )
    {
    char buff[128] = {0};
    printf("input:\n");

    fgets(buff,128,stdin);

    if ( strncmp(buff,"end",3) == 0 )
    {
        break;
    }

    sendto(sockfd,buff,strlen(buff),0,(struct ckaddr*)&saddr,sizeof(saddr));
    memset(buff,0,128);

    int len = sizeof(saddr);
    recvfrom(sockfd,buff,127,0,(struct sockaddr*)&saddr,&len);

    printf("buff=%s\n",buff);
    }

    close(sockfd);

}

服务器端

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    assert( sockfd != -1 );

    struct sockaddr_in saddr,caddr;
    memset(&saddr,0,sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6000);
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
    assert( res != -1 );

    while( 1 )
    {
        int len = sizeof(caddr);
        char buff[128] = {0};
        recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr,&len);
        printf("ip:%s,port:%d,buff=%s\n",inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port),buff );

        sendto(sockfd,"ok",2,0,(struct sockaddr*)&caddr,sizeof(caddr));
    }

    close(sockfd);
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们