Linux Ubuntu 上的套接字(不允许操作)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11178970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:01:55  来源:igfitidea点击:

Sockets on Ubuntu (operation not permitted)

clinuxsocketsubuntu

提问by binariti

I'm newbee and just making my first steps in c++ under linux. So I have some task about sockets. I'm following guides, especially thisone. And code examples are not working. I started with this:

我是新手,刚刚开始在 linux 下使用 C++。所以我有一些关于套接字的任务。我正在遵循指南,尤其是这个指南。并且代码示例不起作用。我从这个开始:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCK_PATH "echo_socket"

int main(void)
{
    int s, s2, t, len;
    struct sockaddr_un local, remote;
    char str[100];

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    local.sun_family = AF_UNIX;
    strcpy(local.sun_path, SOCK_PATH);
    unlink(local.sun_path);
    len = strlen(local.sun_path) + sizeof(local.sun_family);
    if (bind(s, (struct sockaddr *)&local, len) == -1) {
        perror("bind");
        exit(1);
    }
return 0;
}

I've figured out that to compile it (Code::Blocks) there must be one more include:

我发现要编译它 (Code::Blocks) 还必须包含以下内容:

#include <unistd.h>

But after successful run I'm getting message "Bind: Operation not permitted". What is wrong? I've tried to run it under root and still it is not working.

但成功运行后,我收到消息“绑定:不允许操作”。怎么了?我试图在 root 下运行它,但它仍然无法正常工作。

回答by user3387542

Some Unix systems won't allow you to create sockets everywhere. Make sure you have the right permissions and the right file system underneath. (Fat32 as it is used on sdcards in mobile phones won't allow additional flags to files and might get you into trouble) Finally on newer systems there are security things running like selinux which might block the creation of sockets.

某些 Unix 系统不允许您在任何地方创建套接字。确保您拥有正确的权限和正确的文件系统。(Fat32 用于移动电话的 sdcard 不允许附加标志到文件,可能会给您带来麻烦)最后,在较新的系统上,有一些安全性的东西在运行,例如 selinux,它可能会阻止套接字的创建。

On my example I had to change

在我的例子中,我不得不改变

#define SOCK_PATH "echo_socket"

to

#define SOCK_PATH "/dev/socket/echo_socket"

after that it worked immediately. (executable started in root shell)

之后它立即起作用。(可执行文件在 root shell 中启动)

回答by Aaron Duan

Because of no permission. You can #define SOCK_PATH "/home/username/echo_socket"and it will run normally.

因为没有权限。你可以 #define SOCK_PATH "/home/username/echo_socket",它会正常运行。