我正在使用Mono开发一个Linux应用程序并且偶然发现了这个问题。我想创建一个IP套接字以与其他进程进行本地通信,但Bind方法失败并带有无用的消息。我写了一个示例文件来展示这个问题。这是代码:
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();
}
}
以下是异常消息:
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
答案 0 :(得分:1)
127.0.0.1
不是Unix端点。请改用AddressFamily.InterNetwork
。
此外,没有理由使用原始套接字。只需使用TcpListener
/ TcpClient
。