简体   繁体   中英

Socket.Bind() throws “Invalid parameters” exception

I am developing a Linux application with Mono and stumbled into this. I want to create an IP socket to communicate locally with other processes, but the Bind method fails with a not-helpful message. 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. Use AddressFamily.InterNetwork instead.

Also, there's no reason to use raw sockets. Just use TcpListener / TcpClient .

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