c++ - linux bind don't create socket -
i having weird problem. trying create unix socket in directory not create 1 want. have cut down code below example.
#include <iostream> #include <string> #include <cstdlib> #include <string.h> #include <sys/un.h> #include <sys/socket.h> #include <errno.h> #include <limits.h> int main(int argc, char *argv[]) { std::string socketname(argv[1]); socketname += "my_socket"; int fd; int result; struct sockaddr_un addr; fd = socket(af_unix, sock_stream, 0); if (fd == -1) { std::cerr << "socket returned " << errno << ": " << strerror(errno) << std::endl; exit(1); } memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = af_unix; strncpy(addr.sun_path, socketname.c_str(), sizeof(addr.sun_path) - 1); result = bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)); if (result == -1) { std::cerr << "bind returned " << errno << ": " << strerror(errno ) << std::endl; exit(1); } return 0; }
the problem when run program like
./a.out /home/rasterblaster/local/media/video/television/unitedstates/series/californication/seasonone/xvid-conversions
i not "my_socket". instead find random socket named "xvid-convers".
/home/rasterblaster/local/media/video/television/unitedstates/series/californication/seasonone$ ls -la drwxrwxrwx 3 rasterblaster rasterblaster 4096 2012-03-08 22:06 . drwxrwxrwx 3 rasterblaster rasterblaster 4096 2012-03-08 21:39 .. srwxrwxr-x 1 rasterblaster rasterblaster 0 2012-03-08 22:06:08 xvid-convers drwxrwxrwx 2 rasterblaster rasterblaster 4096 2012-03-08 21:39 xvid-conversions
what doing wrong?
there nothing weird going on. if @ result of sizeof(addr.sun_path)
should 100 or bytes. when try copy more size strncpy()
truncating path fits sun_path , bind() creating filesystem entry name beyond last valid directory name.
there no benefit placing socket deep directory structure. can put in /tmp or /run or common directory clients , server have permission if want bit more security.
also, want
socketname += "/my_socket"; // prefix slash
just in case path named passed doesn't end in slash.
Comments
Post a Comment