- Can not connect to Linux «abstract» unix socket
- 4 Answers 4
- cannot connect to linux tcp socket app from remote host
- UNIX socket connection refused
- Ошибка «unable to connect to socket: Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. (10061)» (РЕШЕНО)
- Связанные статьи:
- connection error in unix domain socket implemented in c (gcc) centos 7
- 2 Answers 2
Can not connect to Linux «abstract» unix socket
I’m trying to use UNIX sockets for inter-thread communication. The program is only intended to run on Linux. To avoid creating the socket files, I wanted to use «abstract» sockets, as documented in unix(7). However, I don’t seem to be able to connect to these sockets. Everything works if I’m using «pathname» sockets, though. Here is the code (I haven’t quoted any error handling, but it’s done): thread#1:
int log_socket = socket(AF_LOCAL, SOCK_STREAM, 0); struct sockaddr_un logaddr; socklen_t sun_len = sizeof(struct sockaddr_un); logaddr.sun_family = AF_UNIX; logaddr.sun_path[0] = 0; strcpy(logaddr.sun_path+1, "futurama"); bind(log_socket, &logaddr, sun_len); listen(log_socket, 5); accept(log_socket, &logaddr, &sun_len); . // send - receive
struct sockaddr_un tolog; int sock = socket(AF_LOCAL, SOCK_STREAM, 0); tolog.sun_family = AF_UNIX; tolog.sun_path[0] = 0; strcpy(tolog.sun_path+1, "futurama"); connect(sock, (struct sockaddr*)&tolog, sizeof(struct sockaddr_un));
If all I do in the above code, is change the sun_path to not have leading \0, things work perfect. strace output:
t1: socket(PF_FILE, SOCK_STREAM, 0) = 0 t1: bind(0, , 110) t1: listen(0, 5) t2: socket(PF_FILE, SOCK_STREAM, 0) = 1 t2: connect(1, , 110 t2: ) = -1 ECONNREFUSED (Connection refused) t1: accept(0,
I know that the connect comes before accept, that’s not an issue (I tried making sure that accept() is called before connect(), same result. Also, things are fine if the socket is «pathname» anyway).
For communication between threads of the same process, an ordinary pipe(2) should be enough! And you could also use pipes if all the communicating processes and/or threads have the same parent process!
@BasileStarynkevitch pipe will not work in my case. I need multiple threads to send info, and receive a synchronous response before moving on.
@BasileStarynkevitch for this, I will have to know in advance how many maximum pipes to open, or limit access to one using locks. The socket approach has less overhead for such case.
4 Answers 4
While I was posting this question, and re-reading unix(7) man page, this wording caught my attention:
an abstract socket address is distinguished by the fact that sun_path[0] is a null byte (’\0’). All of the remaining bytes in sun_path define the «name» of the socket
So, if I bzero’ed the sun_path before filling in my name into it, things started to work. I figured that’s not necessarily straight-forward. Additionally, as rightfully pointed out by @davmac and @StoneThrow, the number of those «remaining bytes» can be reduced by specifying only enough length of the socket address structure to cover the bytes you want to consider as your address. One way to do that is to use SUN_LEN macro, however, the first byte of the sun_path will have to be set to !0, as SUN_LEN uses strlen .
If sun_path[0] is \0, The kernel uses the entirety of the remainder of sun_path as the name of the socket, whether it’s \0-terminated or not, so all of that remainder counts. In my original code I would zero the first byte, and then strcpy() the socket name into the sun_path at position 1. Whatever gibberish that was in sun_path when the structure was allocated (especially likely to contain gibberish since it’s allocated on the stack), and was included in the length of the socket structure (as passed to the syscalls), counted as the name of the socket, and was different in bind() and connect().
IMHO, strace should fix the way it displays abstract socket names, and display all the sun_path bytes from 1 to whatever the structure length that was supplied, if sun_path[0] is 0
cannot connect to linux tcp socket app from remote host
I wrote an app that uses a TCP socket from the GNU C socket library. It just basically listens on a socket for incoming requests. I am able to connect to the socket with telnet on the localhost, but when I try connecting from another machine there is no response. I’m running Fedora 13 and disabled my firewall, but it still doesn’t work. The socket code is encapsulated in a library that was written by some other organization and is supposed to work already, but here’s the meat of it:
. fd_ = ::socket(AF_INET, SOCK_STREAM, 0); if (fd_ < 0) < perror("socket"); return -1; >int val = 1; int rc = setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); if (rc < 0) < perror("sesockopt"); close(); return -1; >rc = setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); if (rc < 0) < perror("sesockopt"); close(); return -1; >const int flags = ::fcntl(fd_, F_GETFL, 0); ::fcntl(fd_, F_SETFL, flags | O_NONBLOCK); rc = ::bind(fd_, addr, addr.size_); if (rc < 0) < perror("bind"); close(); return -1; >rc = ::listen(fd_, 10); if (rc < 0) < perror("bind"); close(); return -1; >return 0;
well i’m using 127.0.0.1 for the ip. The socket code belongs to a library that was written by another organization a while back, and it is supposed to work.
127.0.0.1 is the loopback device and only acessible from the local host. you could use 0.0.0.0 to listen on all devices or specify the address of the concrete network interface you want to listen on.
UNIX socket connection refused
Under OS-X, I’ve got process named ‘listener’ that is waiting on ‘accept’ to read data from local unix socket named listener_socket. unfortunately, any attempt to connect that socket terminate in ‘connection refused’ error. Using lsof, to make sure that the ‘listener’ actually listen to this socket :
sudo lsof -p 570 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME . listener 570 root 3u unix 0x48a2751a1bad61ef 0t0 /private/var/run/my_sockets/listener_socket
file /private/var/run/my_sockets/listener_socket /private/var/run/my_sockets/listener_socket: socket
However, it still fail to connect, even when i’m using an alternative way from command like (using socat command)
sudo socat LOCAL:/private/var/run/my_sockets/listener_socket,interval=1 EXEC:'aaaaaaaaaaaaaaaaa',nofork 2015/11/23 00:57:33 socat[928] E connect(3, LEN=49 AF=1 "/private/var/run/my_sockets/listener_socket", 49): Connection refused
perhaps there are more i can do to figure out why i cannot send data to the socket, even-though it’s obvious that ‘listener’ waiting for this data on the other side ? here’s the relevant part of my code : sender:
sockfd = socket(PF_UNIX, SOCK_STREAM, 0); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "%s", LISTENER_SOCKET_PATH); connect(sockfd, (struct sockaddr *) &address, sizeof(struct sockaddr_un) write .
fd = socket(PF_UNIX, SOCK_STREAM, 0); unlink(sock_name); // in case the socket is used before listen(server->fd, 5); // we don't reach 5 listeners for sure . chmod(sock_name, mode); // giving root privilages accept(server->fd, (struct sockaddr *) &server->address, &server->address_length); read .
Ошибка «unable to connect to socket: Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. (10061)» (РЕШЕНО)
WSL2 — это подсистема Windows для Linux, которая позволяет запускать подобия дистрибутивов Linux прямо в Windows не используя виртуальные машины.
По умолчанию дистрибутивы запускаются с интерфейсом командной строки, но это ограничение можно обойти, запустив на Linux сервер RDP (удалённый рабочий стол) или VNC, а затем подключившись к нему используя соответствующий клиент.
Для Kali Linux этот процесс был значительно автоматизирован и упрощён, подробности описаны в статье «Как установить Kali Linux с Win-KeX (графический интерфейс) в WSL2 (подсистему Windows для Linux)».
После установки Win-KeX для запуска графического интерфейса достаточно запустить Kali Linuxв WSL2:
А затем внутри Kali Linux выполнить команду:
После этого должен открыться графический интерфейс.
Но иногда это не происходит и появляется ошибка:
unable to connect to socket: Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. (10061)
В командной строке выводится:
TigerVNC Viewer 32-bit v1.10.80 Built on: 2020-06-15 22:33 Copyright (C) 1999-2020 TigerVNC Team and many others (see README.rst) See https://www.tigervnc.org for information on TigerVNC. Fri Sep 11 06:41:39 2020 DecodeManager: Detected 12 CPU core(s) DecodeManager: Creating 4 decoder thread(s) Fri Sep 11 06:41:41 2020 CConn: unable to connect to socket: Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. (10061)
Для исправления этой ошибки нажмите Ctrl+c.
Эта команда может вывести что-то вроде следующего:
Killing Win-KeX process ID 1618. which was already dead Cleaning stale pidfile '/home/mial/.vnc/HackWare-MiAl.localdomain:1.pid'! Cleaning stale x11 lock '/tmp/.X1-lock'! Cleaning stale x11 lock '/tmp/.X11-unix/X1'!
Вновь попробуйте открыть графический интерфейс:
На этот раз всё должно заработать:
Причина ошибки до конца не ясна — возможно, дело в неудачном старте VNC сервера или процесса Win-KeX, на это указывает строка «Win-KeX process ID 1618… which was already dead», то есть процесс уже мёртвый.
Командой kex stop мы принудительно останавливаем Win-KeX, который при следующем запуске работает нормально.
Связанные статьи:
connection error in unix domain socket implemented in c (gcc) centos 7
I have checked the path «/tmp/dsock» and the socket file «dsock» is there but looking inside the file shows:
File: ‘dsock’ Size: 0 Blocks: 0 IO Block: 4096 socket Device: 801h/2049d Inode: 1572866 Links: 1 Access: (0777/srwxrwxrwx) Uid: ( 7418/user) Gid: (25/group) Access: 2017-08-31 17:16:29.569038461 -0600 Modify: 2017-08-31 17:16:29.569038461 -0600 Change: 2017-09-01 13:28:07.162071494 -0600 Birth: -
Can’t find what the error is. The client side also shows similar connection error. Is it due to the UNIX domain socket file permission issues?
The first step in tackling these kind of problems is ALWAYS to see the error that the system returned. Most UNIX system calls will set errno to give specific error details when they return -1 on error. You should: 1) Include errno.h 2) Log detailed error messages using: printf(«Error %d: %s\n», errno, strerror(errno)); This should ideally be done as part of the routine system call error check
2 Answers 2
You cannot call connect on a listening socket. Once you have bound and listened, the only thing you should do with a listening socket is call accept (or close or use its descriptor in a select ).
So the server should create the socket, bind its address, listen on it and then the server should be sitting («blocked») in the accept function. That is, it’s waiting for a connection, usually in a loop.
Then (after the server has been started and is waiting) your client needs to create its own socket and call connect on it — specifying the same address that the server used when it called bind . This will cause the accept call in the server to return a new socket descriptor for a socket that is actually connected to the client. This is the one that you will use send and recv on for communication. (And the client’s socket will also be connected.)
At this point, the listening socket in the server will still be available to accept additional connections (each of which would return its own new unique socket descriptor).
Although possible, it doesn’t really make sense for the server to connect to its own listening socket endpoint anyway. What would be the point?