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.
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.
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);
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.
Related
I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
Console.WriteLine("The server is running at port 13...");
Console.WriteLine("The local End point is -" +
tcpListener.LocalEndpoint);
output = "Waiting for a connection...";
Console.WriteLine(output);
Socket s = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
catch (Exception e)
{
output = "Error: " + e.ToString();
Console.WriteLine(output);
}
}
On the Java side, I have created a socket which listens to the same host and port -
Socket socket;
try {
socket = new Socket( "localhost", 13);
System.out.println("Connection established");
BufferedReader input =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?
I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.
My code can't receive UDP messages from outside my home net. The communication is between Android and Java computer application, with IP inside my LAN (for example 192.168.0.3) the code works, if I put my Java computer application inside my online server (and obviously I changed every IP with external IPs) this doesn't work; Android can send but it can't receive.
Android code :
#Override
protected Integer doInBackground(Void... params) {
DatagramSocket socket = null;
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket = new DatagramSocket(25565);
} catch (Exception e) {
Log.i("Ex ", "");
}
while (true) {
try {
socket.receive(packet);
String message = new String(packet.getData(), 0,packet.getLength());
Log.i("message", "" + message);
} catch (IOException e) {
Log.i("IO Ex", "");
}
catch (Exception e){
}
}
}
Java computer application code :
http://pastebin.com/2hVGeP6R
192.168.0.X is an internal NAT address. Any network can use it, but it can't be reached from anywhere outside. You either need to configure your router to pass it through to your PC and hit the router's external IP, or you need a real network address.
Read carefully this example. I suppose you that you are trying to read and write in the same socket while it is open. In case it not working paste some more code in order to help you
I am triying to comunicate 2 machines through datagram sockets but I guess I am missing something...
Machine A is runs an Android App (client)
Machine B is a server writen in Python
I can send a message from A to B without any problem, but A never gets the answer from B, the code is the following:
Client (Java) :
InetAddress serverAddr = InetAddress.getByName("10.0.0.10");
DatagramSocket socket = new DatagramSocket();
byte[] bufSent = "register".getBytes();
DatagramPacket dpSent = new DatagramPacket(bufSent,bufSent.length, serverAddr, 8088);
socket.send(dpSent);
byte[] bufRecv = new byte[1024];
DatagramPacket dpReceive = new DatagramPacket(bufRecv, bufRecv.length);
socket.receive(dpReceive);
String serverMessage = new String(dpReceive.getData(), 0, dpReceive.getLength());
Log.v(LOGTAG, "Received " + serverMessage);
Server (Python):
import socket
UDP_IP_DEST = "10.0.0.11"
UDP_IP = "10.0.0.10"
UDP_PORT = 8088
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
if data:
print "received message:", data
sock.sendto("I got the message", (UDP_IP_DEST, UDP_PORT))
Does anyone see where is the mistake? The point is that I have tried to send the answer to another machine instead of the mobile and it works fine.
Thanks a lot.
I had a similar problem with receiving, here's some code we use in our app for Datagrams modified with your values, you can see we do a few things differently in the socket set up. mSocket is just a private DatagramSocket member variable. Give it a try. I think you might need to bind, and possible set the reuse address flag.
try
{
mSocket = new DatagramSocket(null);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(false);
mSocket.bind(new InetSocketAddress(8088));
//Set a 1.5 second timeout for the coming receive calls
mSocket.setSoTimeout(1500);
String data = "myData";
DatagramPacket udpPacket = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getByName("10.0.0.10"), 8088);
mSocket.send(udpPacket);
byte[] buf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(buf, buf.length);
mSocket.receive(recvPacket);
String response = new String(recvPacket.getData());
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I'm trying to make a script that telnet ip port to see if the server is up or down. (like how you do in window command prompt. cmd [enter] => telnet 11.111.11.11 200 (ip& port)and if the the connection is successful, program will return true else false. I need this code to be really efficient since this function will go into the forloop where I do all the displays on the website for each ip. Thnx in advance
P.S
Ops I meant java/jsp my bad haha
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}
I want to solve my problem using and I use java programming language.
Just try to connect to them with a Socket. If you don't get a ConnectException, something is listening st that TCP port. Then do the server a favor and close the socket immediately.
What's the purpose exactly?
This is a simple code to connect to a socket with a timeout
// Create a socket with a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
// Could not reach host - network error.
} catch (IOException e) {
// Network error
}
You can just run this code in a loop to check a series of ports.
NOTE: real portscanners are much more sophisticated: http://art-exploitation.org.ua/7261final/lib0021.html