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

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

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

但我在发布后获得的是:

socket() Failed: Operation not permitted

我知道只有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,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:~$

相关文章

ubuntu退出redis的示例:指定配置文件方式启动源码redis:roo...
ubuntu中mysql改密码忘了的解决方法:1.在终端中切换到root权...
ubuntu安装mysql失败的解决方法原因:可能是原有的MySQL还有...
使用centos和ubuntu建站的区别有以下几点1.CentOS是Linux发行...
ubuntu图形界面和字符界面切换的方法:可以通过快捷键CTRL+A...
ubuntu中重启mysql失败的解决方法1.首先,在ubuntu命令行中,...