我正在尝试在此端口上接收UDP数据包:8070
我有一个发送UDP数据包的程序,我将在另一个程序(Receiver)中接收数据,但我找不到发件人的IP地址! 我正在使用套接字,我的代码就是:
Socket UdpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8070);
byte[] buf = new byte[1000];
public Form1()
{
InitializeComponent();
UdpListener.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
UdpListener.Bind(ipep);
}
private void button1_Click(object sender, EventArgs e)
{
UdpListener.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(OnRecv), UdpListener);
}
private void OnRecv(IAsyncResult ar)
{
UdpListener.EndReceive(ar);
UdpListener.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(OnRecv), UdpListener);
}
我会收到数据但我怎样才能找到发件人IP地址?
我试过这个:
Socket s = (Socket)ar.AsyncState;
MessageBox.Show(s.RemoteEndPoint.ToString());
但是我得到了这个错误:
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
答案 0 :(得分:0)
您应该使用UdpListener.BeginReceiveFrom
代替UdpListener.BeginReceive
,因为它提供了对发送端点的引用。