0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

linux > udp > recvfrom() > 同じPCから: 受信成功 / 別のPCから: 受信失敗

Last updated at Posted at 2015-11-11
動作確認
CentOS 6.5

UDP受信のC実装を試す。python実装が失敗している原因の追究のため。

udp.c
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <arpa/inet.h>
# include <sys/socket.h>

# define SIZE_BUF 200

int main(void)
{
    unsigned short port = 9880;
    struct sockaddr_in rcvAddr;
    int sockfd, slen, rcvdLen;
    char rcvBuf[SIZE_BUF];
    int ret;

    slen = sizeof(rcvAddr);

    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd == -1) {
        exit(EXIT_FAILURE);
    }
    memset((char *) &rcvAddr, 0, sizeof(rcvAddr));     
    rcvAddr.sin_family = AF_INET;
    rcvAddr.sin_port = htons(port);
    rcvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(sockfd , (struct sockaddr*)&rcvAddr, sizeof(rcvAddr) );

    while(1) {
        fflush(stdout);
        rcvdLen = recvfrom(sockfd, rcvBuf, SIZE_BUF, 0, 
            (struct sockaddr *) &rcvAddr, &slen);
        if (rcvdLen == -1) {
            close(sockfd);
            exit(EXIT_FAILURE);
        }
        if (strstr(rcvBuf, "req") == NULL) {    // accept only "req"
            continue;
        }
        printf("rx: %s", rcvBuf);

        // remove <LF>
        if (rcvBuf[rcvdLen - 2] == '\n') {
            rcvBuf[rcvdLen - 2] = 0x00;
        }
        strcat(rcvBuf, ",OK\n");

        ret = sendto(sockfd, rcvBuf, strlen(rcvBuf)+1, 0, 
            (struct sockaddr*) &rcvAddr, slen);         
        if (ret == -1) {
            close(sockfd);
            exit(EXIT_FAILURE);
        }
    }
    close(sockfd);
    return 0;
}

ポート9880へ送ればいい。

  • 同じPCから

    • echo "req" | nc -u 192.168.124.139 9880 : 受信成功
    • echo "req" | nc -u 127.0.0.1 9880 : 受信成功
  • 別のPCから : 受信失敗

別のPCからCentOSへのポートが閉じているのかもしれない。

空きポートのチェックは以下でやっている。
http://qiita.com/7of9/items/e70588e500894c278ee2

やはりCentOSで使うポートが閉じていた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?