学习UDP

2018-12-04 07:14:50来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

参考博客: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;
}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:一个C语言萌新的学习之旅(持续更新中...)

下一篇:Visual Studio编译C工程出现的错误