在 C 中,setsockopt 对于 IPPROTO_TCP IP_TOS 失败
我的代码失败了。我以 root 身份运行(与普通用户的行为相同)
首先我想设置 TOS,然后获取值。
int tos_local = 0x28;
if (setsockopt(sockfd, IPPROTO_TCP, IP_TOS, &tos_local, sizeof(tos_local))) {
error("error at socket option");
} else {
int tos=0;
int toslen=0;
if (getsockopt(sockfd, IPPROTO_TCP, IP_TOS, &tos, &toslen) < 0) {
error("error to get option");
}else {
printf ("changing tos opt = %d\n",tos);
}
}
printf 打印
更改为 opt = 0
我希望打印 0x28 (40)。
问题是什么?
正确答案:
if (setsockopt(sockfd, **IPPROTO_IP**, IP_TOS, &tos_local, sizeof(tos_local))) {
int tos=0;
int toslen=sizeof(tos); //that line here
if (getsockopt(sockfd, IPPROTO_IP, IP_TOS, &tos, &toslen) < 0) {
My code fails. I am running as root (same behavior as normal user)
First I want to set the TOS and then get the value.
int tos_local = 0x28;
if (setsockopt(sockfd, IPPROTO_TCP, IP_TOS, &tos_local, sizeof(tos_local))) {
error("error at socket option");
} else {
int tos=0;
int toslen=0;
if (getsockopt(sockfd, IPPROTO_TCP, IP_TOS, &tos, &toslen) < 0) {
error("error to get option");
}else {
printf ("changing tos opt = %d\n",tos);
}
}
the printf prints
changing tos opt = 0
I would expect to print 0x28 (40).
What is the problem?
The correct answer:
if (setsockopt(sockfd, **IPPROTO_IP**, IP_TOS, &tos_local, sizeof(tos_local))) {
int tos=0;
int toslen=sizeof(tos); //that line here
if (getsockopt(sockfd, IPPROTO_IP, IP_TOS, &tos, &toslen) < 0) {
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IP_TOS
具有级别IPPROTO_IP
,而不是IPPROTO_TCP
。请参阅文档。
这会影响设置和获取选项。
另外,Seth 所说的初始化长度参数,仅影响
getsockopt
。IP_TOS
has levelIPPROTO_IP
, notIPPROTO_TCP
.See the documentation.
This affects both setting and getting the option.
Also, what Seth said about initializing the length parameter, which affects only
getsockopt
.调用getsockopt时,传入&tos指向的内存大小。换句话说,将 toslen 初始化为 sizeof(tos)。
When calling getsockopt, you pass in the size of the memory pointed to by &tos. In other words initialize toslen to sizeof(tos).