SocketException: "access denied" while opening port using UdpClient

Viewed 687

I'm trying to start listening on one of UDP ports on Android device. I'm using Xamarin.Forms and I'm testing it on physical android phone.

public void StartListening(int port = 13000)
{
    ListenerPort = port;
    udpClient = new UdpClient(ListenerPort);

    udpClient.BeginReceive(new AsyncCallback(handleIncomingMessages), null);
}

This function is being used on application start:

public partial class App : Application
{
    [...]
    protected override void OnStart()
    {
        network.StartListening(LISTENING_ON_PORT);
    }
}

The are many similar questions on SO, but most of them were solved by adding INTERNET permission to android manifest. Here is mine:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.ddand">
  <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
  <application android:label="ddAnd.Android" android:theme="@style/MainTheme"></application>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</manifest>

What I see after deploying my app is:

System.Net.Sockets.SocketException: 'Access denied'

and no other details provided.

I've thought my port is being used by another process, but I've check many of them (outside of 1-1024 range) and using all of them gave the same results.

Are there any other reasons for this exception? Do you have any ideas how can I throubleshoot the problem (e.g. how to find available port)?

EDIT:

As suggested in comments, I tried to gain access at runtime (though it should not be necessary, INTERNET permission is granted by default by Xamarin in Debug mode).

This line returns information that permission is granted.

var havePermission = ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet);

Nevertheless I tried to manually get access at runtime

ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Internet }, 1);

Result is the same as before.

1 Answers

Can you try with the following code? (adapted from the documentation)

public void StartListening(int port = 13000)
{
    ListenerPort = port;
    IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ListenerPort);
    udpClient = new UdpClient(ipEndPoint);
    
    UdpState udpState = new UdpState();
    udpState.e = ipEndPoint;
    udpState.u = udpClient;

    udpState.BeginReceive(new AsyncCallback(handleIncomingMessages), udpState);
}
Related