recv
Section: System Calls (2)
Updated: 2025-10-29
Index
JM Home Page
roff page
名前
recv, recvfrom, recvmsg - ソケットからメッセージを受け取る
ライブラリ
標準 C ライブラリ (libc,~-lc)
書式
#include <sys/socket.h>
ssize_t recv(size_t size;
int sockfd, void buf[size], size_t size,
int flags);
ssize_t recvfrom(size_t size;
int sockfd, void buf[restrict size], size_t size,
int flags,
struct sockaddr *_Nullable restrict src_addr,
socklen_t *_Nullable restrict addrlen);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
説明
recv(), recvfrom(), recvmsg() コールは、 ソケットからメッセージを受け取るのに使用される。
これらはコネクションレス型のソケットにも接続指向 (connection-oriened) 型のソケットにも使用できる。 このページでは、まずこれら 3
つのシステムコールすべてに共通の機能について説明し、 システムコール間の違いについて説明する。
The only difference between recv() and read(2) is the presence of
flags. With a zero flags argument, recv() is generally equivalent
to read(2) (but see NOTES). Also, the following call
recv(sockfd, buf, size, flags);
は以下と等価である。
recvfrom(sockfd, buf, size, flags, NULL, NULL);
All three calls return the size of the message on successful completion. If
a message is too long to fit in the supplied buffer, excess bytes may be
discarded depending on the type of socket the message is received from.
If no messages are available at the socket, the receive calls wait for a
message to arrive, unless the socket is nonblocking (see fcntl(2)), in
which case the value -1 is returned and errno is set to EAGAIN or
EWOULDBLOCK. The receive calls normally return any data available, up to
the requested amount, rather than waiting for receipt of the full amount
requested.
アプリケーションは select(2), poll(2), epoll(7)
を使って、ソケットにさらにデータが到着しているかを判定することができる。
フラグ引数
flags 引数には、以下の値を 1つ以上、ビット単位の論理和 を取ったものを指定する:
- MSG_CMSG_CLOEXEC (recvmsg() のみ; Linux 2.6.23)
-
(unix(7) で説明されている) SCM_RIGHTS 操作を使って UNIX ドメインのファイルディスクリプター経由で受信した
ファイルディスクリプターについて close-on-exec フラグをセットする。 このフラグは、 open(2) の O_CLOEXEC
フラグと同じ理由で有用である。
- MSG_DONTWAIT (Linux 2.2 以降)
-
Enables nonblocking operation; if the operation would block, the call fails
with EAGAIN or EWOULDBLOCK. This provides similar behavior to setting
the O_NONBLOCK flag (via the fcntl(2) F_SETFL operation), but
differs in that MSG_DONTWAIT is a per-call option, whereas O_NONBLOCK
is a setting on the open file description (see open(2)), which will
affect all threads in the calling process as well as other processes that
hold file descriptors referring to the same open file description.
- MSG_ERRQUEUE (Linux 2.2 以降)
-
このフラグを指定すると、 キューに入れられたエラーをソケットのエラーキューから取りだせるようになる。 このエラーは補助メッセージに組み込まれて渡され、
この補助メッセージの種別はプロトコルに依存する (IPv4 の場合は IP_RECVERR)。
ユーザーは十分なサイズのバッファーを用意しなければならない。 補助メッセージに関するより詳細な情報は cmsg(3) および ip(7)
を参照のこと。 エラーの原因となったオリジナルパケットのペイロードは、 msg_iovec 経由で通常のデータとして渡される。
エラーを起こしたデータグラムのオリジナルの宛先アドレスは、 msg_name 経由で参照できる。
-
このエラーは sock_extended_err 構造体で提供される:
-
#define SO_EE_ORIGIN_NONE 0
#define SO_EE_ORIGIN_LOCAL 1
#define SO_EE_ORIGIN_ICMP 2
#define SO_EE_ORIGIN_ICMP6 3
struct sock_extended_err
{
uint32_t ee_errno; /* Error number */
uint8_t ee_origin; /* Where the error originated */
uint8_t ee_type; /* Type */
uint8_t ee_code; /* Code */
uint8_t ee_pad; /* Padding */
uint32_t ee_info; /* Additional information */
uint32_t ee_data; /* Other data */
/* More data may follow */
};
struct sockaddr *SO_EE_OFFENDER(struct sock_extended_err *);
-
ee_errno contains the errno number of the queued error. ee_origin
is the origin code of where the error originated. The other fields are
protocol-specific. The macro SO_EE_OFFENDER returns a pointer to the
address of the network object where the error originated from given a
pointer to the ancillary message. If this address is not known, the
sa_family member of the sockaddr contains AF_UNSPEC and the other
fields of the sockaddr are undefined. The payload of the packet that
caused the error is passed as normal data.
-
ローカルなエラーの場合はアドレスは渡されない (これは cmsghdr の cmsg_len メンバーでチェックできる)。受信エラーの場合は
MSG_ERRQUIE フラグが msghdr
にセットされる。エラーが渡された後には、キューに入っている次のエラーに基いて、処理待ちのソケットエラーが再生成され、次のソケット操作の際に渡される。
- MSG_OOB
-
このフラグは、通常のデータストリームでは受信できない 帯域外 (out-of-band) データの受信を要求する。 プロトコルによっては、
通常のデータキューの先頭に速達データを置くものがあるが、 そのようなプロトコルではこのフラグは使用できない。
- MSG_PEEK
-
このフラグを指定すると、 受信キューの最初のデータを返すとき、キューからデータを削除しない。
したがって、この後でもう一度受信コールを呼び出すと、同じデータが返ることになる。
- MSG_TRUNC (Linux 2.2 以降)
-
For raw (AF_PACKET), Internet datagram (since Linux 2.4.27/2.6.8),
netlink (since Linux 2.6.22), and UNIX datagram as well as sequenced-packet
(since Linux 3.4) sockets: return the real size of the packet or datagram,
even when it was longer than the passed buffer.
-
Internet ストリームソケットでの利用については tcp(7) を参照。
- MSG_WAITALL (Linux 2.2 以降)
-
This flag requests that the operation block until the full request is
satisfied. However, the call may still return less data than requested if a
signal is caught, an error or disconnect occurs, or the next data to be
received is of a different type than that returned. This flag has no effect
for datagram sockets.
recvfrom()
recvfrom() places the received message into the buffer buf. The
caller must specify the size of the buffer in size.
src_addr が NULL 以外で、下層のプロトコルからメッセージの送信元アドレスが分かる場合、 この送信元アドレスが src_addr
が指すバッファーに格納される。 この場合、 addrlen は入出力両用の引数となる。 呼び出し前に、呼び出し元は src_addr
に割り当てたバッファーの大きさで初期化しておくべきである。 返ってくる時には、 addrlen
は送信元アドレスの実際の大きさに変更される。渡されたバッファーが小さ過ぎる場合には、返されるアドレスの末尾は 切り詰められる。この場合には、
addrlen では、呼び出し時に渡された値よりも大きな値が返される。
呼び出し元が送信元アドレスを必要としない場合は、 src_addr と addrlen には NULL を指定すべきである。
recv()
recv() コールは通常 接続済みの (connected) ソケットに対してのみ使用される (connect(2)
参照)。次の呼び出しと等価である。
recvfrom(fd, buf, size, flags, NULL, NULL);
recvmsg()
recvmsg() コールは、直接渡す引数の数を減らすために msghdr 構造体を使用する。この構造体は
<sys/socket.h> で以下のように定義されている:
struct msghdr {
void *msg_name; /* Optional address */
socklen_t msg_namelen; /* Size of address */
struct iovec *msg_iov; /* Scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* Ancillary data, see below */
size_t msg_controllen; /* Ancillary data buffer size */
int msg_flags; /* Flags on received message */
};
The msg_name field points to a caller-allocated buffer that is used to
return the source address if the socket is unconnected. The caller should
set msg_namelen to the size of this buffer before this call; upon return
from a successful call, msg_namelen will contain the size of the returned
address. If the application does not need to know the source address,
msg_name can be specified as NULL.
msg_iov と msg_iovlen フィールドは scatter-gather 用の場所を指定する。 readv(2)
に説明がある。
The field msg_control, which has size msg_controllen, points to a
buffer for other protocol control-related messages or miscellaneous
ancillary data. When recvmsg() is called, msg_controllen should
contain the size of the available buffer in msg_control; upon return from
a successful call it will contain the size of the control message sequence.
メッセージの形式は以下の通り:
struct cmsghdr {
size_t cmsg_len; /* Data byte count, including header
(type is socklen_t in POSIX) */
int cmsg_level; /* Originating protocol */
int cmsg_type; /* Protocol-specific type */
/* followed by
unsigned char cmsg_data[]; */
};
補助データは、 cmsg(3) に定義されたマクロ経由でのみアクセスすべきである。
As an example, Linux uses this ancillary data mechanism to pass extended
errors, IP options, or file descriptors over UNIX domain sockets. For
further information on the use of ancillary data in various socket domains,
see unix(7) and ip(7).
msghdr の msg_flags フィールドは recvmsg()
からのリターン時に設定される。ここにはいくつかのフラグが入る。
- MSG_EOR
-
indicates end-of-record; the data returned completed a record (generally,
used with sockets of type SOCK_SEQPACKET).
- MSG_TRUNC
-
データグラムが与えられたバッファーより大きかったために、 データグラムのはみ出した部分が捨てられたことを示す。
- MSG_CTRUNC
-
補助データのためのバッファーが不足したために、 制御データの一部が捨てられたことを示す。
- MSG_OOB
-
速達データや帯域外データを受信したことを示す。
- MSG_ERRQUEUE
-
データは受信しなかったが ソケットのエラーキューから拡張エラーを受信したことを示す。
- MSG_CMSG_CLOEXEC (since Linux 2.6.23)
-
indicates that MSG_CMSG_CLOEXEC was specified in the flags argument of
recvmsg().
返り値
これらのコールは受信したバイト数を返す。 エラーの場合は -1 を返し、 errno にエラーを示す値を設定する。
ストリームソケットの接続相手が正しくシャットダウンを実行した場合は、
返り値は 0 (昔ながらの "end-of-file" の戻り値) となる。
Datagram sockets in various domains (e.g., the UNIX and Internet domains)
permit zero-size datagrams. When such a datagram is received, the return
value is 0.
ストリームソケットに対する受信要求バイト数が 0 だった場合も、 値 0 が返される。
エラー
これらはソケット層で発生する一般的なエラーである。 他のエラーが下層のプロトコルモジュールで生成され、 返されるかもしれない。
それらのマニュアルを参照すること。
- EAGAIN または EWOULDBLOCK
-
ソケットが非停止 (nonblocking) に設定されていて 受信操作が停止するような状況になったか、 受信に時間切れ (timeout)
が設定されていて データを受信する前に時間切れになった。 POSIX.1 は、この場合にどちらのエラーを返すことも認めており、 これら 2
つの定数が同じ値を持つことも求めていない。 したがって、移植性が必要なアプリケーションでは、両方の可能性を 確認すべきである。
- EBADF
-
引数 sockfd が不正なファイルディスクリプターである。
- ECONNREFUSED
-
リモートのホストでネットワーク接続が拒否された (よくある理由としては、要求したサービスが起動されていないなどがある)。
- EFAULT
-
受信バッファーへのポインターがプロセスのアドレス空間外を指している。
- EINTR
-
データを受信する前に、シグナルが配送されて割り込まれた。 signal(7) 参照。
- EINVAL
-
不正な引数が渡された。
- ENOMEM
-
recvmsg() のためのメモリーが確保できなかった。
- ENOTCONN
-
ソケットに接続指向プロトコルが割り当てられており、 まだ接続されていない (connect(2) と accept(2)
を参照のこと)。
- ENOTSOCK
-
ファイルディスクリプター sockfd がソケットを参照していない。
バージョン
According to POSIX.1, the msg_controllen field of the msghdr structure
should be typed as socklen_t, and the msg_iovlen field should be typed
as int, but glibc currently types both as size_t.
標準規格
POSIX.1-2024.
歴史
POSIX.1-2001, 4.2BSD.
POSIX.1 では、 MSG_OOB, MSG_PEEK, MSG_WAITALL フラグだけが記載されている。
注意
If a zero-size datagram is pending, read(2) and recv() with a
flags argument of zero provide different behavior. In this circumstance,
read(2) has no effect (the datagram remains pending), while recv()
consumes the pending datagram.
recvmmsg(2) には、一度の呼び出しでの複数のデータグラムに使用できる Linux 固有の システムコールに関する情報が書かれている。
例
recvfrom() の利用例が getaddrinfo(3) に記載されている。
関連項目
fcntl(2), getsockopt(2), read(2), recvmmsg(2), select(2),
shutdown(2), socket(2), cmsg(3), sockatmark(3), ip(7),
ipv6(7), socket(7), tcp(7), udp(7), unix(7)
Index
- 名前
-
- ライブラリ
-
- 書式
-
- 説明
-
- フラグ引数
-
- recvfrom()
-
- recv()
-
- recvmsg()
-
- 返り値
-
- エラー
-
- バージョン
-
- 標準規格
-
- 歴史
-
- 注意
-
- 例
-
- 関連項目
-
This document was created by
man2html,
using the manual pages.