简体   繁体   English

Socket.Bind()引发“无效参数”异常

[英]Socket.Bind() throws “Invalid parameters” exception

I am developing a Linux application with Mono and stumbled into this. 我正在用Mono开发Linux应用程序,但偶然发现了这一点。 I want to create an IP socket to communicate locally with other processes, but the Bind method fails with a not-helpful message. 我想创建一个IP套接字以与其他进程进行本地通信,但是Bind方法失败,并显示一条无用的消息。 I have written a sample file that showcases this problem. 我写了一个样本文件来说明这个问题。 Here is the code: 这是代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class Test
{
    private static EndPoint EP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 23515);
    private static Socket Server;

    private static void InitServer()
    {
        Server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
        Server.Bind(EP);
        Server.Listen(1000);
        Console.WriteLine("Server started.");

        while (true)
        {
            Console.WriteLine("Waiting for a connection...");
            var handler = Server.Accept();
            string data = null;

            while (true)
            {
                var bytes = new byte[1024];
                int length = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, length);

                if (data.IndexOf("<EOF>") > -1)
                    break;
            }

            Console.WriteLine("Received message: " + data);
        }
    }

    public static void Main(string[] args)
    {
        InitServer();
    }
}

And here is the exception message: 这是异常消息:

Unhandled Exception:
System.Net.Sockets.SocketException: Invalid arguments
  at System.Net.Sockets.Socket.Bind (System.Net.EndPoint local_end) <0x407e6910 + 0x000ef> in <filename unknown>:0
  at Test.InitServer () <0x407bc270 + 0x0006b> in <filename unknown>:0
  at Test.Main (System.String[] args) <0x407b9d50 + 0x0000b> in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.Net.Sockets.SocketException: Invalid arguments
  at System.Net.Sockets.Socket.Bind (System.Net.EndPoint local_end) <0x407e6910 + 0x000ef> in <filename unknown>:0
  at Test.InitServer () <0x407bc270 + 0x0006b> in <filename unknown>:0
  at Test.Main (System.String[] args) <0x407b9d50 + 0x0000b> in <filename unknown>:0

127.0.0.1 is not a Unix endpoint. 127.0.0.1不是Unix端点。 Use AddressFamily.InterNetwork instead. 请改用AddressFamily.InterNetwork

Also, there's no reason to use raw sockets. 另外,没有理由使用原始套接字。 Just use TcpListener / TcpClient . 只需使用TcpListener / TcpClient

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM