【发布时间】:2014-03-30 12:28:35
【问题描述】:
我正在尝试在此端口接收 UDP 数据包:8070
我有一个发送 UDP 数据包的程序,我将在另一个程序(接收方)中接收数据,但我找不到发送方 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
【问题讨论】: