2012-11-12 33 views
1

我在一些移植(套接字相關)的Windows C代碼的Linux/Android的的過程中,我遇到與ioctl命令的問題:的Android/Linux的ioctl的FIONREAD失敗

unsigned long u; 

if(sockfd != -1 && !ioctl(sockfd, FIONREAD, &u)) 

{ 
    return((long) u); 
} 
    ... 
// throw exception 

當我檢查errno時,我看到EINVAL,但我不明白爲什麼調用ioctl時失敗了這些參數。我甚至試圖將你聲明爲int,但它仍然失敗。我不知道什麼是錯的。這段代碼在Windows上運行得非常好(ioctlsocket代替ioctl)。

下面是一個使用strace從Linux的:

socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 3 
bind(3, {sa_family=AF_INET, sin_port=htons(9099), sin_addr=inet_addr("0.0.0.0")}, 16) = 0 
listen(3, 5)       = 0 
ioctl(3, FIONREAD, [1])     = -1 EINVAL (Invalid argument) 
write(2, "Exception code: 00000503, data: "..., 52Exception code: 00000503, data: 00000000 ((null):0) 
) = 52 
shutdown(3, 2 /* send and receive */) = 0 
close(3)        = 0 
exit_group(1)       = ? 

回答

1

Linux不上監聽套接字支持FIONREAD/SIOCINQ。請參閱tcp(7)

 
SIOCINQ 
     Returns the amount of queued unread data in the receive buffer. The 
     socket must not be in LISTEN state, otherwise an error (EINVAL) is 
     returned. SIOCINQ is defined in <linux/sockios.h>. Alternatively, you 
     can use the synonymous FIONREAD, defined in <sys/ioctl.h>. 
+0

簡單地忽略EINVAL是否安全? –