Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to establish UDP socket connection

Tags:

c#

sockets

udp

Unhandled Exception: System.Net.Sockets.SocketException: The attempted operation is not supported for the type of object referenced

I have tried mapping the ip to V6 same exception

namespace ConsoleApp1
{
    using System.Net;
    using System.Net.Sockets;
    using static Tools;

    class Program
    {

        static void Main(string[] args)
        {
            Send("Hello from Server");

            Socket socket = new Socket(GetRemote().AddressFamily, SocketType.Dgram, ProtocolType.Udp);

            socket.Bind(GetRemote());

            socket.Listen(10);
        }
    }

    static class Tools
    {
        private static readonly EndPoint _REMOTE = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], 11039);

        public static void Send(string message)
        {
            Console.Out.Write(message + Console.Out.NewLine);
        }

        public static EndPoint GetRemote()
        {
            return _REMOTE;
        }
    }
}
like image 684
Todor Yanev Avatar asked Jan 21 '26 13:01

Todor Yanev


2 Answers

If you debug your code you can see that the issue occurs in the socket.Listen(10); call. Basically you should not use Listen with UDP connection. You can use the RecieveFrom function instead.

See https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket?view=netframework-4.7.2

like image 169
gpro Avatar answered Jan 23 '26 01:01

gpro


Change your socket definition to this:

Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

EDIT:

Using what @gpro said, the problem is on listen and you should use receivefrom instead:

Here is an example how to use a good udp socket connection: https://gist.github.com/darkguy2008/413a6fea3a5b4e67e5e0d96f750088a9

like image 42
Mikev Avatar answered Jan 23 '26 02:01

Mikev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!