为什么我不能在 Ubuntu 中创建原始套接字? [英] Why I cant create raw socket in Ubuntu?

查看:34
本文介绍了为什么我不能在 Ubuntu 中创建原始套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning how to work with raw sockets in Linux. I'm trying to create a socket like that:

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

但我在发布后得到的是:

But all I got after launch is:

socket() 失败:不允许操作

socket() failed: Operation not permitted

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

I know that only root can create raw sockets, but if I run it with SUID bit or sudo - the problem is the same. What's wrong? The system is Ubuntu 11.04.

也许我包含了不必要的标题?

Maybe I'm including needless headers?

#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 没用?

And I'm wondering - why SUID is useless?

推荐答案

我的钱因为你没有正确运行你的代码.

My money on you not running your code correctly.

我已将您的确切代码复制并粘贴到一个空的 main() 中.如果我自己运行它,我会得到同样的错误,但它在 sudo 下正确运行.这是在 Ubuntu 上.

I've copied and pasted your exact code into an empty main(). I get the same error if I run it as myself, but it runs correctly under sudo. This is on 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 身份运行:

Run as root:

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

这篇关于为什么我不能在 Ubuntu 中创建原始套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆