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

时间:2009-12-22 19:28:17

标签: c# linux sockets mono

我正在尝试调整我找到的用于连接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#中执行此操作?这是我第一次涉及套接字编程,所以请指出任何明显的错误。

1 个答案:

答案 0 :(得分:4)

您需要使用Mono.Posix.dll中的Mono.Unix.UnixEndPoint而不是IPEndPoint。其他一切都是一样的。请参阅XSP如何使用它的示例here