• linux下udp编程


    #include<sys/types.h>
    #include<sys/socket.h>
    #include<unistd.h>
    #include<netinet/in.h>
    #include<arpa/inet.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<errno.h>
    #include<netdb.h>
    #include<stdarg.h>
    #include<string>
    #include<iostream>
    #include<cstring>
    
       /* 创建UDP套接口 */
        struct sockaddr_in server_addr;
        memset(&server_addr,0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        server_addr.sin_port = htons(port);
    
    
        /* 创建socket */
        int server_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if(server_socket_fd == -1)
        {
            perror("Create Socket Failed:");
            exit(1);
        }
    
    
        /* 绑定套接口 */
        if(-1 == (bind(server_socket_fd,(struct sockaddr*)&server_addr,sizeof(server_addr))))
        {
            perror("Server Bind Failed:");
            exit(1);
        }
    
    
        struct sockaddr_in client_addr;
        socklen_t client_addr_length = sizeof(client_addr);
    
        //设置超时
        struct timeval tv_out;
        tv_out.tv_sec = 3;//等待10秒
        tv_out.tv_usec = 0;
        setsockopt(server_socket_fd,SOL_SOCKET,SO_RCVTIMEO,&tv_out, sizeof(tv_out));
    
    
        /* 接收数据 */
        memset(buffer,0, lenbuff);
        if(recvfrom(server_socket_fd, buffer, lenbuff,0,(struct sockaddr*)&client_addr, &client_addr_length) == -1)  //MSG_DONTWAIT  将0换为MSG_DONTWAIT就是非阻塞模式,可能会cpu占用过高问题
        {
            if(errno!=EAGAIN)  //阻塞不设置超时时,不用判断,直接去掉该判断,保留子语句
            {
                perror("Receive Data Failed:");
                exit(1);
            }
        }
        close(server_socket_fd);
    
  • 相关阅读:
    mysql函数
    maven 配置自动本地/线上不同配置自动打包
    maven clean后 编译报错
    htmlunit填坑
    java正则表达式移除网页中注释代码
    spark 计算结果写入mysql 案例及常见问题解决
    pychrome激活
    hadoop集群常见问题解决
    hadoop+spark集群搭建
    C++:构造函数2——拷贝构造函数
  • 原文地址:https://www.cnblogs.com/ggzone/p/5170972.html
Copyright © 2020-2023  润新知