recvのヘルプ・マニュアル
日本語 英語
recv --help
man recv
RECV(2) Linux Programmer’s Manual RECV(2)
名前
recv, recvfrom, recvmsg - ソケットからメッセージを受け取る
書式
#include
#include
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
説明
recvfrom() と recvmsg() コールは、ソケットからメッセージを受け取るのに
使用する。またソケットのデータ受信にも使うことができ、このときソケッ ト
は接続指向 (connection-oriened) であってもなくてもよい。
src_addr が NULL 以外で、下層のプロトコルから送信元アドレスが分かる場合
、 src_addr にはこの送信元アドレスが入れられる。 src_addr が NULL の 場
合、 src_addr には何も入らない。この場合、 addrlen は使用されず、この引
き数は NULL にしておくべきである。引き数 addrlen は入出力両用の引き数で
あ る。呼び出し時には、呼び出し元が src_addr に割り当てたバッファの大き
さで初期化しておくべきである。返ってくる時には、送信元アドレスの実際 の
大 きさに変更される。渡されたバッファが小さ過ぎる場合には、返されるアド
レスの末尾は切り詰められる。この場合には、 addrlen では、呼び出し時に渡
された値よりも大きな値が返される。
recv() コールは通常 接続済みの (connected) ソケット (connect(2) を参照)
についてのみ使用され、 src_addr 引き数に NULL を指定した recvfrom() と
等価である。
こ れらの三つのルーチンはいずれも、成功した場合にはメッセージの長さを返
す。メッセージが長過ぎて指定されたバッファに入り切らなかった場合には 、
メ ッセージを受信したソケットの種類によっては余分のバイトが捨てられるか
もしれない。
ソケットに受け取るメッセージが存在しなかった場合、受信用のコールはメ ッ
セ ージが到着するまで待つ。ただし、ソケットが非停止 (non-blocking) に設
定されていた場合 (fcntl(2) を参照) は -1 を返し、外部 変 数 errno に
EAGAIN か EWOULDBLOCK を設定する。これらの受信用のコールは、受信したデ
ータのサイズが要求したサイズに達するまで待つのではなく、何らかのデー タ
を 受信すると復帰する (受信されるデータの最大サイズは要求したサイズであ
る)。
select(2) や poll(2) コールを使って、次のデータがいつ届くかを判断できる
。
recv() コールの flags 引き数には、以下の値を 1つ以上、ビット単位の OR (
論理和) を取ったものを指定する:
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 以降)
非停止 (non-blocking) 操作を有効にする。操作が停止するような場合
にエラー EAGAIN か EWOULDBLOCK で呼び出しが失敗する (fcntl(2) の
F_SETFL で O_NONBLOCK フラグを指定することによっても有効にでき
る)。
MSG_ERRQUEUE (Linux 2.2 以降)
このフラグを指定すると、キューに入れられたエラーをソケットのエラ
ーキューから取りだせるようになる。このエラーは補助メッセージに組
み込まれて渡され、この補助メッセージの種別はプロトコルに依存する
(IPv4 の場合は IP_RECVERR)。ユーザは十分なサイズのバッファを用意
しなければならない。補助メッセージに関するより 詳 細 な 情 報 は
cmsg(3) および ip(7) を参照のこと。エラーの原因となったオリジナ
ルパケットのペイロードは、 msg_iovec 経由で通常のデータとして 渡
される。エラーを起こしたデータグラムのオリジナルの宛先アドレスは
、 msg_name 経由で参照できる。
ローカルなエラーの場合はアドレスは渡されない (これは cmsghdr の
cmsg_len メ ン バ ー で チ ェ ッ クできる)。受信エラーの場合は
MSG_ERRQUIE が msghdr にセットされる。エラーが渡された後には、キ
ューに入っている次のエラーに基いて、処理待ちのソケット・エラーが
再生成され、次のソケット操作の際に渡される。
このエラーは 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 にはキューに入れられたエラーの errno が入っ て い る 。
ee_origin に は エラーが発生した場所のオリジン・コード (origin
code) が入っている。他のフィールドはプロトコル 依 存 で あ る 。
SO_EE_OFFENDER マクロは、この補助的なメッセージを引き数に取って
、エラーの発生したネットワークオブジェクトのアドレスへのポインタ
を 返す。アドレスが不明の場合には、 sockaddr の sa_family メンバ
ーが AF_UNSPEC になっている。 sockaddr の他のフィールドは不定 で
ある。エラーの発生したパケットのペイロードは通常のデータとして渡
される。
ローカルでのエラーの場合にはアドレスは渡されない (これは cmsghdr
の cmsg_len メンバーでチェックできる)。エラーを受け取った場合、
MSG_ERRQUEUE が msghdr に設定される。エラーが渡された後には、 処
理待ちになっていたソケット・エラーが、キューに入っている次のエラ
ーに基づいて再生成され、次のソケット操作の際に渡される。
MSG_OOB
このフラグは、通常のデータ・ストリームでは受信できな い 帯 域 外
(out-of-band) データの受信を要求する。プロトコルによっては、通常
のデータ・キューの先頭に速達データを置くものがあるが、そのような
プロトコルではこのフラグは使用できない。
MSG_PEEK
このフラグを指定すると、受信キューの最初のデータを返すとき、キュ
ーからデータを削除しない。したがって、この後でもう一度受信コール
を呼び出すと、同じデータが返ることになる。
MSG_TRUNC (Linux 2.2 以降)
raw ソ ケット (AF_PACKET)、 Internet datagram ソケット (Linux
2.4.27/2.6.8 以降)、 netlink (Linux 2.6.22 以降) ソケットの場 合
、パケットやデータグラムの長さが渡したバッファよりも長かった場合
にも、パケットやデータグラムの実際の長さを返す。 Unix ドメインソ
ケット (unix(7)) ソケットについては実装されていない。
Internet ストリームソケットでの利用については tcp(7) を参照。
MSG_WAITALL (Linux 2.2 以降)
このフラグは、要求した量いっぱいのデータが到着するまで、操作を停
止 (block) するよう要求する。但し、シグナルを受信したり、エラ ー
や切断 (disconnect) が発生したり、次に受信されるデータが異なる型
だったりした場合には、要求した量よりデータが少なくても返ることが
ある。
recvmsg() コールは、直接渡す引き数の数を減らすために msghdr 構造体を使
用する。この構造体は で以下のように定義されている:
struct iovec { /* Scatter/gather array items */
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
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 */
socklen_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};
msg_name と msg_namelen は、ソケットが接続されていない場合に送信元の ア
ド レスを指定する。名前が必要ない場合には msg_name に NULL ポインタを指
定する。 msg_iov と msg_iovlen フィールドは readv(2) に記述されているよ
う な 分 解/ 結 合 用のベクトル (scatter-gather locations) を指定する。
msg_control フィールドは msg_controllen の長さを持ち、他のプロトコル 制
御 メ ッ セ ー ジや種々の補助データのためのバッファへのポインタである。
recvmsg() を呼ぶ際には、 msg_controllen に msg_control のバッファの長さ
を 入れておく必要がある。コールが成功して返った場合、制御メッセージ列の
長さが入っている。
メッセージの形式は以下の通り:
struct cmsghdr {
socklen_t cmsg_len; /* data byte count, including hdr */
int cmsg_level; /* originating protocol */
int cmsg_type; /* protocol-specific type */
/* followed by
unsigned char cmsg_data[]; */
};
補助データは、 cmsg(3) に定義されたマクロ経由でのみアクセスすべきである
。
例をあげると、 Linux はこの補助データのメカニズムを、 Unix ソケット上で
の拡張エラーや IP オプション、ファイル・ディスクリプタの受け渡しに利 用
している。
msghdr の msg_flags フィールドは recvmsg() からのリターン時に設定される
。ここにはいくつかのフラグが入る。
MSG_EOR
これはレコードの終り (end-of-record) を示し、返されたデータが 完
全なレコードであることを示す (一般的には SOCK_SEQPACKET 型のソケ
ットで使用される)。
MSG_TRUNC
データグラムが与えられたバッファより大きかったために、データグラ
ムのはみ出した部分が捨てられたことを示す。
MSG_CTRUNC
補助データのためのバッファが不足したために、制御データの一部が捨
てられたことを示す。
MSG_OOB
速達データや帯域外データを受信したことを示す。
MSG_ERRQUEUE
データは受信しなかったがソケットのエラー・キューから拡張エラーを
受信したことを示す。
返り値
こ れらのコールは受信したバイト数を返す。エラーの場合は -1 を返す。接続
先が正しくシャットダウンを実行した場合は、返り値は 0 となる。
エラー
これらはソケット層で発生する一般的なエラーである。他のエラーが下層の プ
ロ トコル・モジュールで生成され、返されるかもしれない。それらのマニュア
ルを参照すること。
EAGAIN または EWOULDBLOCK
ソケットが非停止 (non-blocking) に設定されていて受信操作が停止す
る ような状況になったか、受信に時間切れ (timeout) が設定されてい
てデータを受信する前に時間切れになった。 POSIX.1-2001 は、この場
合 にどちらのエラーを返すことも認めており、これら 2 つの定数が同
じ値を持つことも求めていない。したがって、移植性が必要なアプリケ
ーションでは、両方の可能性を確認すべきである。
EBADF 引き数 sockfd が不正なディスクリプタである。
ECONNREFUSED
リモートのホストでネットワーク接続が拒否された (よくある理由とし
ては、要求したサービスが起動されていないなどがある)。
EFAULT 受信バッファへのポインタがプロセスのアドレス空間外を指している。
EINTR デ ー タを受信する前に、シグナルが配送されて割り込まれた。 sig-
nal(7) 参照。
EINVAL 不正な引き数が渡された。
ENOMEM recvmsg() のためのメモリが確保できなかった。
ENOTCONN
ソケットに接続指向プロトコルが割り当てられており、まだ接続されて
いない (connect(2) と accept(2) を参照のこと)。
ENOTSOCK
引き数 sockfd がソケットを参照していない。
準拠
4.4BSD (これらの関数は 4.2BSD で現われた), POSIX.1-2001。
POSIX.1-2001 では、 MSG_OOB, MSG_PEEK, MSG_WAITALL フラグだけが記載され
ている。
注意
上記のプロトタイプは glibc2 にしたがっている。 Single Unix Specifica-
tion でも同様だが、返り値の型が ssize_t となっている (一方で 4.x BSD や
libc4 や libc5 は全て int を使用している)。 flags 引き数は 4.x BSD では
int だ が、libc4 と libc5 では unsigned int である。 len 引き数は 4.x
BSD では int だが、 libc4 と libc5 では size_t である。 addrlen 引き 数
は 4.x BSD, libc4, libc5 では int * である。現在の socklen_t * は POSIX
で発案された。 accept(2) も参照すること。
POSIX.1-2001 では、構造体 msghdr の フ ィ ー ル ド msg_controllen は
socklen_t 型であるべきだとされているが、現在の glibc (glibc 2.4) では
size_t 型である。
例
recvfrom() の利用例が getaddrinfo(3) に記載されている。
関連項目
fcntl(2), getsockopt(2), read(2), select(2), shutdown(2), socket(2),
cmsg(3), sockatmark(3), socket(7)
Linux 2008-12-03 RECV(2)
RECV(2) Linux Programmer’s Manual RECV(2)
NAME
recv, recvfrom, recvmsg - receive a message from a socket
SYNOPSIS
#include
#include
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
DESCRIPTION
The recvfrom() and recvmsg() calls are used to receive messages from a
socket, and may be used to receive data on a socket whether or not it
is connection-oriented.
If src_addr is not NULL, and the underlying protocol provides the
source address, this source address is filled in. When src_addr is
NULL, nothing is filled in; in this case, addrlen is not used, and
should also be NULL. The argument addrlen is a value-result argument,
which the caller should initialize before the call to the size of the
buffer associated with src_addr, and modified on return to indicate the
actual size of the source address. The returned address is truncated
if the buffer provided is too small; in this case, addrlen will return
a value greater than was supplied to the call.
The recv() call is normally used only on a connected socket (see con-
nect(2)) and is identical to recvfrom() with a NULL src_addr argument.
All three routines return the length of the message on successful com-
pletion. If a message is too long to fit in the supplied buffer,
excess bytes may be discarded depending on the type of socket the mes-
sage is received from.
If no messages are available at the socket, the receive calls wait for
a message to arrive, unless the socket is non-blocking (see fcntl(2)),
in which case the value -1 is returned and the external variable 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.
The select(2) or poll(2) call may be used to determine when more data
arrives.
The flags argument to a recv() call is formed by OR’ing one or more of
the following values:
MSG_CMSG_CLOEXEC (recvmsg() only; since Linux 2.6.23)
Set the close-on-exec flag for the file descriptor received via
a Unix domain file descriptor using the SCM_RIGHTS operation
(described in unix(7)). This flag is useful for the same rea-
sons as the O_CLOEXEC flag of open(2).
MSG_DONTWAIT (since Linux 2.2)
Enables non-blocking operation; if the operation would block,
the call fails with the error EAGAIN or EWOULDBLOCK (this can
also be enabled using the O_NONBLOCK flag with the F_SETFL
fcntl(2)).
MSG_ERRQUEUE (since Linux 2.2)
This flag specifies that queued errors should be received from
the socket error queue. The error is passed in an ancillary
message with a type dependent on the protocol (for IPv4
IP_RECVERR). The user should supply a buffer of sufficient
size. See cmsg(3) and ip(7) for more information. The payload
of the original packet that caused the error is passed as normal
data via msg_iovec. The original destination address of the
datagram that caused the error is supplied via msg_name.
For local errors, no address is passed (this can be checked with
the cmsg_len member of the cmsghdr). For error receives, the
MSG_ERRQUEUE is set in the msghdr. After an error has been
passed, the pending socket error is regenerated based on the
next queued error and will be passed on the next socket opera-
tion.
The error is supplied in a sock_extended_err structure:
#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_ori-
gin is the origin code of where the error originated. The other
fields are protocol-specific. The macro SOCK_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 sock-
addr 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.
For local errors, no address is passed (this can be checked with
the cmsg_len member of the cmsghdr). For error receives, the
MSG_ERRQUEUE is set in the msghdr. After an error has been
passed, the pending socket error is regenerated based on the
next queued error and will be passed on the next socket opera-
tion.
MSG_OOB
This flag requests receipt of out-of-band data that would not be
received in the normal data stream. Some protocols place expe-
dited data at the head of the normal data queue, and thus this
flag cannot be used with such protocols.
MSG_PEEK
This flag causes the receive operation to return data from the
beginning of the receive queue without removing that data from
the queue. Thus, a subsequent receive call will return the same
data.
MSG_TRUNC (since Linux 2.2)
For raw (AF_PACKET), Internet datagram (since Linux
2.4.27/2.6.8), and netlink (since Linux 2.6.22) sockets: return
the real length of the packet or datagram, even when it was
longer than the passed buffer. Not implemented for Unix domain
sockets.
For use with Internet stream sockets, see tcp(7).
MSG_WAITALL (since 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 discon-
nect occurs, or the next data to be received is of a different
type than that returned.
The recvmsg() call uses a msghdr structure to minimize the number of
directly supplied arguments. This structure is defined as follows in
:
struct iovec { /* Scatter/gather array items */
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
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 */
socklen_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};
Here msg_name and msg_namelen specify the source address if the socket
is unconnected; msg_name may be given as a null pointer if no names are
desired or required. The fields msg_iov and msg_iovlen describe scat-
ter-gather locations, as discussed in readv(2). The field msg_control,
which has length 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 length of the
available buffer in msg_control; upon return from a successful call it
will contain the length of the control message sequence.
The messages are of the form:
struct cmsghdr {
socklen_t cmsg_len; /* data byte count, including hdr */
int cmsg_level; /* originating protocol */
int cmsg_type; /* protocol-specific type */
/* followed by
unsigned char cmsg_data[]; */
};
Ancillary data should only be accessed by the macros defined in
cmsg(3).
As an example, Linux uses this auxiliary data mechanism to pass
extended errors, IP options or file descriptors over Unix sockets.
The msg_flags field in the msghdr is set on return of recvmsg(). It
can contain several flags:
MSG_EOR
indicates end-of-record; the data returned completed a record
(generally used with sockets of type SOCK_SEQPACKET).
MSG_TRUNC
indicates that the trailing portion of a datagram was discarded
because the datagram was larger than the buffer supplied.
MSG_CTRUNC
indicates that some control data were discarded due to lack of
space in the buffer for ancillary data.
MSG_OOB
is returned to indicate that expedited or out-of-band data were
received.
MSG_ERRQUEUE
indicates that no data was received but an extended error from
the socket error queue.
RETURN VALUE
These calls return the number of bytes received, or -1 if an error
occurred. The return value will be 0 when the peer has performed an
orderly shutdown.
ERRORS
These are some standard errors generated by the socket layer. Addi-
tional errors may be generated and returned from the underlying proto-
col modules; see their manual pages.
EAGAIN or EWOULDBLOCK
The socket is marked non-blocking and the receive operation
would block, or a receive timeout had been set and the timeout
expired before data was received. POSIX.1-2001 allows either
error to be returned for this case, and does not require these
constants to have the same value, so a portable application
should check for both possibilities.
EBADF The argument sockfd is an invalid descriptor.
ECONNREFUSED
A remote host refused to allow the network connection (typically
because it is not running the requested service).
EFAULT The receive buffer pointer(s) point outside the process’s
address space.
EINTR The receive was interrupted by delivery of a signal before any
data were available; see signal(7).
EINVAL Invalid argument passed.
ENOMEM Could not allocate memory for recvmsg().
ENOTCONN
The socket is associated with a connection-oriented protocol and
has not been connected (see connect(2) and accept(2)).
ENOTSOCK
The argument sockfd does not refer to a socket.
CONFORMING TO
4.4BSD (these function calls first appeared in 4.2BSD), POSIX.1-2001.
POSIX.1-2001 only describes the MSG_OOB, MSG_PEEK, and MSG_WAITALL
flags.
NOTES
The prototypes given above follow glibc2. The Single Unix Specifica-
tion agrees, except that it has return values of type ssize_t (while
4.x BSD and libc4 and libc5 all have int). The flags argument is int
in 4.x BSD, but unsigned int in libc4 and libc5. The len argument is
int in 4.x BSD, but size_t in libc4 and libc5. The addrlen argument is
int * in 4.x BSD, libc4 and libc5. The present socklen_t * was
invented by POSIX. See also accept(2).
According to POSIX.1-2001, the msg_controllen field of the msghdr
structure should be typed as socklen_t, but glibc currently (2.4) types
it as size_t.
EXAMPLE
An example of the use of recvfrom() is shown in getaddrinfo(3).
SEE ALSO
fcntl(2), getsockopt(2), read(2), select(2), shutdown(2), socket(2),
cmsg(3), sockatmark(3), socket(7)
COLOPHON
This page is part of release 3.22 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at http://www.kernel.org/doc/man-pages/.
Linux 2009-03-10 RECV(2)