繁体   English   中英

为什么我不能在Ubuntu中创建原始套接字?

[英]Why I cant create raw socket in Ubuntu?

我正在学习如何在Linux中使用原始套接字。 我正在尝试创建一个这样的套接字:

if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
    perror("socket() failed");
    exit(-1);
}

但是启动后我得到的是:

socket()失败:不允许操作

我知道只有root才能创建原始套接字,但是如果我用SUID位或sudo运行它,问题是一样的。 怎么了? 系统是Ubuntu 11.04。

也许我包括不必要的标题?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>

我想知道-为什么SUID没有用?

我的钱给您,无法正确运行您的代码。

我已经将您的确切代码复制并粘贴到一个空的main() 如果以我自己的身份运行该错误,但在sudo下可以正常运行。 这是在Ubuntu上。

编码:

#include <sys/socket.h>
#include <netinet/in.h>

int main()
{ 
  int sd;
  if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
    perror("socket() failed");
    return -1;
  }
  return 0;
} 

自己运行:

aix@aix:~$ ./a.out 
socket() failed: Operation not permitted
aix@aix:~$

以root身份运行:

aix@aix:~$ sudo ./a.out 
aix@aix:~$

根据人的说法:仅允许有效用户ID为0或CAP_NET_RAW功能的进程打开原始套接字

因此,您可以按照以下建议的方式使用sudo运行应用程序,或为其设置CAP_NET_RAW功能(实际上,您也需要CAP_NET_ADMIN):

# setcap cap_net_raw,cap_net_admin=eip PATH_TO_YOUR_APPLICATION

可以在http://ftp.kernel.org/pub/linux/libs/security/linux-privs/kernel-2.4/capfaq-0.2.txt找到详细信息

标头无论如何都不会影响它。

即使您将添加更多不必要的文件,也不会影响程序的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM