Todor Yanev
Todor Yanev

Reputation: 85

c# How to establish UDP socket connection

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;
        }
    }
}

Upvotes: 3

Views: 2027

Answers (2)

Mikev
Mikev

Reputation: 2082

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

Upvotes: 2

gpro
gpro

Reputation: 592

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

Upvotes: 2

Related Questions