简体   繁体   中英

Can't connect to Unix Socket with C#

I'm trying to attach to a Unix socket that is exposed from a Docker container as a mounted volume. Running the above immediately gives an error: Only one usage of each socket address (protocol.network address/port) is normally permitted

This error happens regardless of whether or not the socket is listening, so it leads me to believe something is going on with Windows 10, and trying to connect to a Unix domain socket with .net5.0. It's almost like it fails trying to allocate a listener, and never even tries to connect. Has anyone else dealt with this, am I missing something??

This seems like a simple enough task, so I'm not sure what the issue is here.

   var socketName = "C:\\Users\\user1\\ipc\\node.socket";
   var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
   socket.Bind(new UnixDomainSocketEndPoint(socketName)); << exception here

Exception:
Only one usage of each socket address (protocol/network address/port) is normally permitted

In my case, I was able to get this to work by using socat and mapping the unix socket file to a TCP connection. This was fairly simple using another container.

##docker-compose.yml
    some-service:
      ...
      volumes: ##map the socket in to a volume
          - socket-vol:/opt/socket/ipc
    socat: ##remap the unix socket to TCP so we can develop against is easily
        image: alpine/socat
        ports:
            - 127:0.0.1:1234:1234
        command: tcp-listen:1234,fork,reuseaddr unix-connect:/opt/socket/ipc/node.socket
        volumes:
            - socket-vol:/opt/socket/ipc

volumes:
    socket-vol:

Then I had to change my C# code to use the new socket type:

var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
client.BeginConnect("127.0.0.1",1234, new AsyncCallback(ConnectCallback), client);

And then I was able to access the socket. @jdweng makes a good point in the original comments that you cannot attach to Unix sockets from a windows machine due to file permissions. Thus, mapping in to a TCP socket lets us sidestep that issue. I will need to alter my code when it is time to create an executable, but this allows me to develop and debug natively in Windows.

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