Why is DatagramSocket not binding to the specified port in my Android app?

I’m experiencing an issue with binding a DatagramSocket to a specific port (40000). Despite my efforts, Wireshark shows that packets are being sent from a different source port. Here is the relevant part of my ConnectDeviceViewModel code:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.s2000mobile.Device
import com.example.s2000mobile.UdpClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.net.SocketException

class ConnectDeviceViewModel : ViewModel() {
    private val _devices = MutableStateFlow(emptyList<Device>())
    val devices: StateFlow<List<Device>> = _devices

    private val _ipAddress = MutableStateFlow("192.168.0.211")
    val ipAddress: StateFlow<String> = _ipAddress

    private val _port = MutableStateFlow(40000)
    val port: StateFlow<Int> = _port

    private val _timeout = MutableStateFlow(500)
    val timeout: StateFlow<Int> = _timeout

    private val _isSearching = MutableStateFlow(false)
    val isSearching: StateFlow<Boolean> = _isSearching

    fun updateIpAddress(newIpAddress: String) {
        _ipAddress.value = newIpAddress
    }

    fun updatePort(newPort: Int) {
        _port.value = newPort
    }

    fun updateTimeout(newTimeout: Int) {
        _timeout.value = newTimeout
    }

    private var searchingProcess: Job? = null
    private val udpClient = UdpClient()

    fun findDevices() {
        if (_isSearching.value) {
            searchingProcess?.cancel()
            _isSearching.value = false
            return
        }

        searchingProcess = viewModelScope.launch {
            _isSearching.value = true
            var socket: DatagramSocket? = null
            try {
                withContext(Dispatchers.IO) {
                    socket = DatagramSocket(null)
                    socket!!.reuseAddress = true
                    socket!!.bind(InetSocketAddress(port.value))

                    for (slaveAddress in 1..247) {
                        if (!isActive) break
                        val data = ByteArray(4)
                        udpClient.sendPacket(
                            socket!!,
                            ipAddress.value,
                            port.value,
                            data
                        )

                        val response = udpClient.recievePacket(socket!!, timeout.value)
                        if (response != null) {
                            _devices.value = _devices.value + Device(slaveAddress, "КДЛ")
                        }
                    }
                }
            } finally {
                socket?.close()
                _isSearching.value = false
            }
        }
    }
}

This is the UdpClient code ConnectDeviceViewModel uses:

import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

class UdpClient {
    fun sendPacket(socket: DatagramSocket, ipAddress: String, port: Int, data: ByteArray) {
        val address = InetAddress.getByName(ipAddress)
        val packet = DatagramPacket(data, data.size, address, port)
        socket.send(packet)
    }

    fun recievePacket(socket: DatagramSocket, timeout: Int): ByteArray? {
        val buffer = ByteArray(14)
        val packet = DatagramPacket(buffer, buffer.size)
        socket.soTimeout = timeout

        return try {
            socket.receive(packet)
            val responseData = packet.data.sliceArray(0 until packet.length)
            responseData
        } catch (e: Exception) {
            null
        }
    }
}

Additional info:

  • socket.localPort method returns 40000
  • NETSTAT shows no information about port 40000
  • I use AVD for debugging

I tried different approaches on specifying port, but none of them worked.

val socket = DatagramSocket(port.value)
var socket: DatagramSocket? = null
socket = DatagramSocket(InetSocketAddress("0.0.0.0", port.value))
var socket: DatagramSocket? = null
socket = DatagramSocket(null)
socket!!.reuseAddress = true
socket!!.bind(InetSocketAddress(port.value))

New contributor

Dmitry Krylov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật