Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
binariti Avatar asked Oct 07 '22 10:10

binariti


2 Answers

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)

like image 166
user3387542 Avatar answered Oct 09 '22 23:10

user3387542


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

like image 25
Aaron Duan Avatar answered Oct 10 '22 00:10

Aaron Duan