【发布时间】:2023-03-24 13:16:01
【问题描述】:
我正在尝试使用 UDPClient 来侦听多播 IP(UDP 端口 3000)数据包。
当我确实运行了发送程序(它也侦听该端口)时,我在 UdpClient listener = ... 线上收到以下错误。
System.Net.Sockets.SocketException:
'Only one usage of each socket address (protocol/network address/port) is normally permitted'
但是,如果它没有运行,我不会收到该错误,但程序会锁定等待数据包到达。
程序全文为:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vtunnel
{
public class UDPListener
{
private const int listenPort = 3000;
private const string multicastIP = "239.0.0.0";
private const string myIP = "10.4.30.239";
public static void StartListener() {
bool done = false;
IPAddress listenAddress;
IPAddress myAddress;
IPAddress.TryParse(multicastIP, out listenAddress);
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(listenAddress, listenPort);
try
{
while (!done)
{
Console.WriteLine("Waiting for multicast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received multicast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
}
class Program
{
static void Main(string[] args)
{
UDPListener.StartListener();
}
}
}
【问题讨论】: