初めて UDP をコーディングする準備として、ここからコピーして軽く変更したクライアントとサーバーのコードの例をいくつか試しています。recvfrom() によって返される値が、読み取ったバイト数ではなく常にバッファーのサイズであることを除いて、すべてが機能しているようです (バッファーサイズを変更して再コンパイルすると、報告された受信バイトは新しいバッファーサイズに一致するように変更されますが、送信されるバイトは、すべてのテストで同じ 10 バイトです)。
このコードに問題を説明するエラーが見られる人はいますか (簡潔にするために、ここでは一部のエラー チェックを削除しています)。参考までに、Yosemite 10.10.5 を実行している Macbook Pro のターミナル ウィンドウで bash をコンパイルして実行しています。
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define BUFLEN 1024
#define PORT 9930
int main(void) {
struct sockaddr_in si_me, si_other;
int s, i, slen=sizeof(si_other);
int nrecv;
char buf[BUFLEN];
s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
bind(s, &si_me, sizeof(si_me));
while (1) {
nrecv = recvfrom(s, buf, BUFLEN, 0, &si_other, &slen);
printf("Received packet from %s:%d\n%d bytes rec'd\n\n",
inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), nrecv);
}
}