recvfrom的addrlen參數

昨天用recvfrom去接收數據,好久沒有過這個函數,按照man的手冊,一個一個傳參,但是遇到一個問題,數據可以接收正常,但是總是errno一直爲22,並且sendto一直失敗返回-1。這裏做一下記錄,提醒自己細節的重視程度決定技術的高度。

函數原型:

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                        struct sockaddr *src_addr, socklen_t *addrlen);

前面幾個參數沒什麼好說,一搜一大把。遇到的問題就在於最後一個參數:socklen_t *addrlen。看到傳入指針,我的第一反應就是,這是一個結果參數,所以初始化完之後直接傳入。導致在之後調用sendto時,一直失敗。後來才發現recvfrom的函數說明中有下面一段話:

recvfrom()

recvfrom() places the received message into the buffer buf. The caller must specify the size of the buffer inlen.

If src_addr is not NULL, and the underlying protocol provides the source address of the message, that source address is placed in the buffer pointed to by src_addr. In this case, addrlen is a value-result argument. Before the call, it should be initialized to the size of the buffer associated with src_addr. Upon return, addrlen is updated to contain 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.

If the caller is not interested in the source address, src_addr and addrlen should be specified as NULL.

真神奇,粗心大意浪費了時間,打自己一下。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章