如何在C#中连接到本地Socket?

4

我正在尝试修改这个我找到的用于连接Dropbox守护程序的Python代码:

def connect(self, cmd_socket="~/.dropbox/command_socket", iface_socket="~/.dropbox/iface_socket"):
    "Connects to the Dropbox command_socket, returns True if it was successfull."
    self.iface_sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    self.sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        self.sck.connect(os.path.expanduser(cmd_socket)) # try to connect
        self.iface_sck.connect(os.path.expanduser(iface_socket))
    except:
        self.connected = False
        return False
    else: # went smooth
        self.connected = True
        return True

以下是我目前的内容:

public bool Connect (int port) {
    return Connect ("~/.dropbox/command_socket", "~/.dropbox/iface_socket",
                    port);
}

public bool Connect (string cmdSocket, string ifaceSocket, int port)
{
    IfaceSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                              ProtocolType.IP);
    CmdSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                            ProtocolType.IP);

    try {
        // ExpandUser replaces a leading "/~" with the user's home directory
        IPAddress [] CmdIPs = Dns.GetHostAddresses (ExpandUser (cmdSocket));
        CmdSocket.Connect (CmdIPs [0], port);
        IPAddress [] IfaceIPs = Dns.GetHostAddresses (ExpandUser (ifaceSocket));
        IfaceSocket.Connect (IfaceIPs [0], port);
    } catch (Exception e) {
        // Debug
        Console.WriteLine (e);

        Connected = false;
        return false;
    }

    Connected = true;
    return true;
}

这段代码可以编译通过,但是在运行时出现了 System.Net.Sockets.SocketException: No such host is known 错误。我猜测这是因为 cmdSocketifaceSocket 是路径而不是 IP 地址。Python 似乎可以自动处理这个问题,那么在 C# 中该怎么做呢?这是我第一次尝试 socket 编程,请指出任何明显的错误。


如果你打算使用IP地址(而不是像Gonzalo的答案那样使用Unix端点),你可能想要指定AddressFamily.InterNetwork。 - itowlson
我不打算使用IP地址。我之前写那些代码只是因为在谷歌上找到了一个例子,但后来发现其实我并不需要它们。 - Matthew
1个回答

4
你需要使用Mono.Posix.dll中的Mono.Unix.UnixEndPoint而不是IPEndPoint。其他都一样。查看XSP如何使用它的示例here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接