Gaming Life

一日24時間、ゲームは10時間

(Linux) UDPを使って一定時間おきに文字列を送信するプログラム

研究室でUDPを使った無線通信の受信側が受信待ち状態にない時のパケットキャプチャをする必要があったので書いた.

劣化iperfにすぎないとか言ってはいけない

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

enum { DEST_PORT = 12345 };

void rand_text(int length, char* result) {
    int i, rnd_int;
    const char char_set[] = "01234567890abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (i = 0; i < length; i++) {
        result[i] = char_set[rand() % strlen(char_set)];
    }
    result[length] = 0;
}

// ./main 192.168.20.2 7360(1パケットあたりのUDPデータ長[Byte]) 1(何秒間隔で送るか) count(合計何回送るか)
int main(int argc, char* argv[]) {
    if (argc < 5) {
        printf("command line arguments is invalid!\n");
        return 1;
    }
    const char* dest_addr = argv[1];
    const int udp_data_len = atoi(argv[2]);
    const int interval_sec = atoi(argv[3]);
    const int count_max = atoi(argv[4]);

    printf("Send random data(%dByte) %dtimes to %s through UDP to every %d sec\n", udp_data_len, count_max, dest_addr, interval_sec);
    char* str;
    str = (char*)malloc(sizeof(char) * udp_data_len);
    srand(time(NULL));
    rand_text(udp_data_len, str);
    printf("create string strlen(%ld)\n", strlen(str));

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(DEST_PORT);
    addr.sin_addr.s_addr = inet_addr(dest_addr);

    int count = 0;
    while (count < count_max) {
        printf("send %ldByte\n", strlen(str));
        sendto(sock, str, strlen(str), 0, (struct sockaddr*)&addr, sizeof(addr));
        printf("----------\n");
        sleep(interval_sec);
        count++;
    }
    free(str);
    return 0;
}

30分程度で書いた使い捨てのプログラム故,エラー処理が一切書いてないのに注意.