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);