简体   繁体   中英

Sockets on Ubuntu (operation not permitted)

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 this one. And code examples are not working. I started with this:

#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:

#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.

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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