android
android

Reputation: 3401

Exception : java.net.BindException: Cannot assign requested address

I want to send and receive datagram socket but I'm getting exception java.net.BindException: Cannot assign requested address. I passed the correct ipaddress of the server which I want to communicate and correct port no.

try {
    SocketAddress sockaddr = new InetSocketAddress("203.100.77.54", 8000);
    DatagramSocket sock = new DatagramSocket(sockaddr);
    DatagramPacket pack = new DatagramPacket(bData, bData.length);
    sock.send(pack);
} catch (FileNotFoundException fnfe) {
    Log.e(LOG_TAG, "FileNotFoundException");
} catch (SocketException se) {
    Log.e(LOG_TAG, "SocketException");
} catch (UnknownHostException uhe) {
    Log.e(LOG_TAG, "UnknownHostException");
} catch (IOException ie) {
    Log.e(LOG_TAG, "IOException");
}

Please help me.

Upvotes: 3

Views: 7081

Answers (3)

pfrank
pfrank

Reputation: 2167

Here's a more high-level answer:

Direct UDP, like direct TCP, is meant for a specific address, like Bob. So if I'm sending the packets to Bob, then you aren't allowed to listen for them -- you can only listen for yourself. So if you try to open a listener for Bob, your device tells you that you aren't allowed.

Unless you are using multicast UDP or something like that, you can only listen to things that are meant to be sent directly to you, hence the IP or whatever address must be that devices own address.

Upvotes: 0

user207421
user207421

Reputation: 310957

DatagramSockets aren't created with a target address. They are created with their own local bind-address, or none, which causes a default bind when first used. The target address is specified when constructing the DatagramPacket, or in the connect() method.

Upvotes: 2

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

try like this

 String messageStr = "Hello Android!";
 int server_port = 8000;
 DatagramSocket s = new DatagramSocket();
 InetAddress local = InetAddress.getByName("203.100.77.54");
 int msg_length = messageStr.length();
 byte[] message = messageStr.getBytes();
 DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
 s.send(p);

Upvotes: 0

Related Questions