C言語-UDPサーバ



UPDサーバ

UDP(IPPROTO_UDP)を指定してデータグラム(SOCK_DGRAM)ソケットを作成します。



サンプル

/*
 *  UDP server
 */

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

struct server_info {
    unsigned short sv_port;
};
typedef struct server_info sv_info_t;

static int
udp_receiver( int sd, char *errmsg )
{
    int rc = 0;
    int exit_flag = 1;
    struct sockaddr_in cl_addr = {0};
    char buff[256];
    unsigned int cl_addr_len = 0;


    while( exit_flag ){
        cl_addr_len = sizeof(cl_addr);

        rc = recvfrom( sd, buff, sizeof(buff), 0,
                       (struct sockaddr *)&cl_addr, &cl_addr_len );
        if( rc < 0 ){
            sprintf( errmsg, "(line:%d) %s", __LINE__, strerror(errno) );
            return( -1 );
        }

        fprintf( stdout, "client: %s\n", inet_ntoa(cl_addr.sin_addr) );
        fprintf( stdout, "  msg: %s\n", buff );
    }

    return( 0 );
}

static int
udp_server( sv_info_t *info, char *errmsg )
{
    struct sockaddr_in sv_addr = {0};
    int sd = 0;
    int rc = 0;

    sd = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP );
    if( sd < 0 ){
        sprintf( errmsg, "(line:%d) %s", __LINE__, strerror(errno) );
        return( -1 );
    }

    memset( &sv_addr, 0, sizeof(sv_addr) );
    sv_addr.sin_family = AF_INET;
    sv_addr.sin_addr.s_addr = htonl( INADDR_ANY );
    sv_addr.sin_port = htons( info->sv_port );

    rc = bind( sd, (struct sockaddr *)&sv_addr, sizeof(sv_addr) );
    if( rc != 0 ){
        sprintf( errmsg, "(line:%d) %s", __LINE__, strerror(errno) );
        goto close_exit;
    }

    rc = udp_receiver( sd, errmsg );
    if( rc != 0 ) goto close_exit;

  close_exit:
    if( sd != 0 ) close( sd );
    return( rc );
}

static int
initialize( int argc, char *argv[], sv_info_t *info )
{
    if( argc != 2 ){
        fprintf( stderr, "Usage: %s <port>\n", argv[0] );
        return( -1 );
    }

    memset( info, 0, sizeof(sv_info_t) );
    info->sv_port = atoi( argv[1] );

    return( 0 );
}

int
main( int argc, char *argv[] )
{
    int rc = 0;
    sv_info_t info = {0};
    char errmsg[256];

    rc = initialize( argc, argv, &info );
    if( rc != 0 ) return( -1 );

    rc = udp_server( &info, errmsg );
    if( rc != 0 ){
        fprintf( stderr, "Error: %s\n", errmsg );
        return( -1 );
    }

    return( 0 );
}



関連

C言語-ソケットプログラミング



スポンサード リンク