C# UDP Socket: Get receiver address

前端 未结 5 1674
萌比男神i
萌比男神i 2020-12-29 07:04

I have an asynchronous UDP server class with a socket bound on IPAddress.Any, and I\'d like to know which IPAddress the received packet was sent to (...or received on). It

5条回答
  •  悲哀的现实
    2020-12-29 07:36

    In regard to the buffer problem try the following:

    Create a class called StateObject to store any data you want to have in your callback, with a buffer, also including the socket if you so need it (as I see that you are currently passing udpSock as your stateObject). Pass the newly created object to the async method and then you will have access to it in your callback.

    public void Starter(){
        StateObject state = new StateObject();
        //set any values in state you need here.
    
        //create a new socket and start listening on the loopback address.
        Socket lSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        lSock.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
    
        EndPoint ncEP = new IPEndPoint(IPAddress.Any, 0);
        lSock.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, SocketFlags.None, ref ncEP,    DoReceiveFrom, state);
    
        //create a new socket and start listening on each IPAddress in the Dns host.
        foreach(IPAddress addr in Dns.GetHostEntry(Dns.GetHostName()).AddressList){
            if(addr.AddressFamily != AddressFamily.InterNetwork) continue; //Skip all but IPv4 addresses.
    
            Socket s = new Socket(addr.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            s.Bind(new IPEndPoint(addr, 12345));
    
            EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
    
            StateObject objState = new StateObject();
            s.BeginReceiveFrom(objState.buffer, 0, objState.buffer.length, SocketFlags.None, ref newClientEP, DoReceiveFrom, objState);
         }
    } 
    

    In searching this question I found:

    http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.beginreceivefrom.aspx

    You can then cast the StateObject from AsyncState as you are currently doing with udpSock and your buffer, as well as anyother data you need would be stored there.

    I suppose that now the only problem is how and where to store the data, but as I don't know your implementation I can't help there.

提交回复
热议问题