linux下udp小例子

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

   /* 创建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);

你可能感兴趣的:(C++)