簡體   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