欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

学习UDP

程序员文章站 2024-01-17 13:42:58
参考博客:https://www.cnblogs.com/skyfsm/p/6287787.html 简单编写了 udp的小程序,udp_client 端通过终端输入字符,然后发送给udp_server。udp_server 接收到后,给udp_client一个响应。 ......

参考博客:https://www.cnblogs.com/skyfsm/p/6287787.html

简单编写了 udp的小程序,udp_client 端通过终端输入字符,然后发送给udp_server。udp_server 接收到后,给udp_client一个响应。 

//socket udp 客户端
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<arpa/inet.h>

int main()
{
    //创建socket对象
    int sockfd=socket(af_inet,sock_dgram,0);
    if(-1 == sockfd)
    {
        printf("socket failed.\n");
    }

    //创建网络通信对象
    struct sockaddr_in ser_addr;
    memset(&ser_addr, 0, sizeof(ser_addr));
    ser_addr.sin_family =af_inet;
    ser_addr.sin_port = htons(8888);//htons(1324);
    ser_addr.sin_addr.s_addr = inet_addr("192.168.7.224"); // inet_addr("127.0.0.1");

    while(1)
    {
        printf("please input a char:");
        char cchar;
        int num = 0;
        char buf[1024];
        scanf("%c",&cchar);
        getchar();
        num = sendto(sockfd, &cchar, sizeof(char), 0, (struct sockaddr*)&ser_addr, sizeof(ser_addr));
        printf("client send %d bytes: %c.\n", num, cchar);

        memset(buf, 0, sizeof(buf));
        num = recvfrom(sockfd,buf,sizeof(buf), 0, null, null);
        printf("client recv %d bytes: %s.\n\n", num, buf);
    }

    close(sockfd);

}
//socket udp 服务端
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<arpa/inet.h>

#define invalid_value -1
#define invalid_socket -1

int main()
{
    int ret = -1;

    //创建socket对象
    int sockfd=socket(af_inet,sock_dgram,0); // af_inet:ipv4;sock_dgram:udp
    if(invalid_socket == sockfd)
    {
        printf("socket failed.\n");
    }

    //创建网络通信对象
    struct sockaddr_in ser_addr;
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family =af_inet;
    ser_addr.sin_port = htons(8888); //端口号,需要网络序转换
    ser_addr.sin_addr.s_addr= htonl(inaddr_any); //ip地址,需要进行网络序转换,inaddr_any:本地地址

    //绑定socket对象与通信链接
    ret =bind(sockfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
    if(0>ret)
    {
        printf("bind error \n");
        return -1;
    }

    char buf[1024];  //接收缓冲区,1024字节
    int count;
    struct sockaddr_in clent_addr;    //clent_addr用于记录发送方的地址信息
    socklen_t len = sizeof(clent_addr);; 

    while(1)
    {
        memset(buf, 0, sizeof(buf));
        count = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&clent_addr, &len);  //recvfrom是拥塞函数,没有数据就一直拥塞
        printf("server recv %d bytes: %s \n",count, buf);

        memset(buf, 0, sizeof(buf));
        snprintf(buf, sizeof(buf), "%s %d %s", "recive", count, "bytes");
        printf("server send string:%s \n", buf);
        sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&clent_addr, len); //发送信息给client,注意使用了clent_addr结构体指针
    }

    close(sockfd);

    return 0;
}