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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With