2013年7月7日日曜日

UDP サーバー Linux用

simple udp server source code for testing.

指定のUDPポートを開いてUDPパケットの受信を待ちます。UDPパケットを受信したら、送信元に対してUDPパケットで応答します。簡単なUDPサーバーです。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main( int argc, char **argv)
{
    int c;
    int i;
    int sock;
    struct sockaddr_in addr;
    char buf[1000];
    char senderstr[512];
    char *ips = "";
    char *ipd = "0.0.0.0";
    int    nPort = 12345;
    int    nCount = 10;
    int    nInt   = 1000;
    int    bReply = 0;
    opterr = 0;
    while(( c = getopt(argc, argv, "s:d:p:n:t:rh")) != -1)
    {
        switch(c)
        {
        case 'h':
            printf(" udpr \n");
            printf(" -s xxx.xxx.xxx.xxx :  server IP [INETADDR_ANY]\n");
            printf(" -p 9999           :  server port [12345]\n");
            printf(" -r                :  Reply packet [No-Reply]\n");
            printf("  \n");
            return 0;
        case 's':
            ips = optarg;
            break;
        case 'd':
            ipd = optarg;
            break;
        case 'p':
            printf("-p %p\n", optarg);
            if (optarg)
                nPort = atol(optarg);
            break;
        case 'n':
            if (optarg)
                nCount = atol(optarg);
            break;
        case 't':
            if (optarg)
                nInt = atol(optarg);
            break;
        case 'r':
            bReply = 1;
            break;
        }
    }
    printf("\n udpr\n");
    printf(" Src = %s, Dst = %s, Port=%d, Count=%d, Interval=%dmsec %s\n", ips, ipd, nPort, nCount, nInt, bReply ? "Reply": " No-Reply");
    sock = socket(AF_INET,SOCK_DGRAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(nPort);
    if (strlen(ips))
        addr.sin_addr.s_addr = inet_addr(ips);
    else
        addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)))
    {
        close(sock);
        printf("bind error  \n");
        return 0;
    }
    printf("--- bind port=%d \n", ntohs(addr.sin_port));

    i = 0;
    while (1)
    {
        int addrlen;
        int reclen;
        memset(buf, 0, sizeof(buf));
        addrlen = sizeof(addr);
        reclen = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&addr, &addrlen);
        inet_ntop(AF_INET, &addr.sin_addr, senderstr, sizeof(senderstr));
        printf("RCV<<<%s", buf);
        printf("... %s %d  len=%d... ", senderstr, ntohs(addr.sin_port), reclen);
        printf("\n");
        if (buf[0] == 'E')
            break;
        if (bReply)
        {
            sprintf(buf, "Reply %04d", i);
            sendto(sock, buf, 256, 0, (struct sockaddr *)&addr, sizeof(addr));
            printf("SND>>>%s", buf);
             printf("... %d\n", 256);
        }
        i++;
    }
   
    close(sock);
    return 1;
}

0 件のコメント:

コメントを投稿