2014-02-27 87 views
0

我想接受此端口上的UDP包:8070C# - UDP的Socket BeginReceive()(查看Ip地址)

我发送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 

回答