I have a sample code as below and the socket is bound to IP 10.10.88.11 and port 9876. I tested with the 2 conditions with wireshark as below. Both PCs are in the same subnet.
Send UDP packet from the same pc (10.10.88.11) - UDP Server able to receive
Send UDP packet from another pc ( 10.10.88.10) - UDP Server unable to receive but Wireshark (at 10.10.88.11) able to capture the packets
I have searched the internet but can't find a solution for this. Is there anything i did wrong in creating the InetScoketAddress?
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String args[]) throws Exception {
InetSocketAddress address = new InetSocketAddress("10.10.88.11", 9876);
DatagramSocket serverSocket = new DatagramSocket(address);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("Waiting to receive");
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
I believe Wireshark is able to grab packets before they are evaluated by the firewall, meaning that you will detect them but they will never reach the java app. Did you try deactivating your firewall ?
Related
I'm using Netbeans IDE trying to make a UDP connection between client and server, it's a simple program that UDPClient send a String to UDPServer and the server capitalize the string and sends it back to the client.I made the client side and server side in a separated projects.
my class code for the client UDPClient :
package udpclient;
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException{
//get input from user
BufferedReader user_in = new BufferedReader(
new InputStreamReader(System.in));
//create udp socket connection
DatagramSocket socket = new DatagramSocket();
//creat buffers to process data
byte[] inData = new byte[1024];
byte[] outData = new byte[1024];
//get ip destination wanted
InetAddress IP = InetAddress.getByName("localhost");
//read data from user
System.out.println("Enter Data to send to server: ");
outData = user_in.readLine().getBytes();
/*
* make pkts for interaction
*/
//send pkts
DatagramPacket sendPkt = new DatagramPacket(outData, outData.length, IP, 9876);
socket.send(sendPkt);
//receive pkts
DatagramPacket recievePkt = new DatagramPacket(inData, inData.length);
socket.receive(recievePkt);
System.out.println("Replay from Server: "+recievePkt.getData());
}
}
and my server side class UDPServer:
package udpserver;
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException{
// TODO code application logic
//connection
DatagramSocket socket = new DatagramSocket();
//pkt buffers
byte[] inServer = new byte[1024];
byte[] outServer = new byte[1024];
//receive pkt
DatagramPacket rcvPkt = new DatagramPacket(inServer,inServer.length);
socket.receive(rcvPkt);
//display receive
System.out.println("Packet Received!");
//retrive pkt info to send response to same sender
InetAddress IP = rcvPkt.getAddress();
int port = rcvPkt.getPort();
//process data
String temp = new String(rcvPkt.getData());
temp = temp.toUpperCase();
outServer = temp.getBytes();
//send response packet to sender
DatagramPacket sndPkt = new DatagramPacket(outServer, outServer.length, IP, port);
socket.send(sndPkt);
}
}
make in count that the program runs normally and outputs no error. the server doesn't receive the packet at all , it didn't interact with the client. why does that happened ?
You haven't specified any listening port in your server so the server listen on a random available port.
Try with this on server side
DatagramSocket socket = new DatagramSocket(9876);
The problem is that your server code doesn't specify a port - it will listen to a random available port, whereas the client is sending to 9876. To correct this, use:
DatagramSocket socket = new DatagramSocket(9876, InetAddress.getByName("localhost"));
(If you're on a linux system) I'd highly recommend using netstat to debug this kind of code:
netstat -ln | grep 9876
will tell you if a process is listening to port 9876.
Another useful tool is netcat, which can be used to send and receive TCP and UDP:
nc -u localhost 9876
allows you to send messages over UDP to the server.
In your client code, you also need to turn the received bytes back into a string to get meaningful output.
I am working on a simple audio streamer with multicast. I wrote serer and client on the same machine, so I worked with localhost and multicast-groups. The system works on one machine but when I tried to use another PC as the server, I can't get them to connect. Here is the situation:
The client first knocks on a tcp-server which lets the client know the multicasting-group IP an port. After this, the client starts listining to the address via multicastSocket.receive();.
Here are the important bits from the system:
(I left out the exceptions and other non-important stuff in the following code)
Server
Important to know is that the "LAN-Connection" is the name of my network interface on the servers system.
int multicastPort = 8888;
InetAddress multicastIP = InetAddress.getbyName("228.5.6.7");
InetSocketAddress multicastAddress = new inetSocketAddress( multicastIP, multicastPort );
NetworkInterface multicastInterface = NetworkInterface.getByName( "LAN-Connection" );
MulticastSocket multicastSocket = new MulticastSocket( multicastPort );
multicastSocket.joinGroup( multicastAddress, multicastIP);
while(true) {
byte [] buffer = audioIn.readBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastIP, multicastPort);
multicastSocket.send(packet );
}
Client
The client requests the multicast-IP and Port from the server. (a tcp-server-thread handles this) Like with the server "LAN-Connection" is the name of the clients network interface.
int multicastPort = server.request("port");
String multicastIP_String = server.request("IP");
InetAddress multicastIP = InetAddress.getbyName(multicastIP_String );
InetSocketAddress multicastAddress = new inetSocketAddress( multicastIP, multicastPort );
NetworkInterface multicastInterface = NetworkInterface.getByName( "LAN-Connection" );
MulticastSocket multicastSocket = new MulticastSocket( multicastPort );
multicastSocket.joinGroup( multicastAddress, multicastIP);
while(true) {
byte [] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
multicastSocket.receive(packet);
}
The TCP connection for requesting / sending the multicast IP and port works. An application called CurrPorts also tells me, that the correct ports get reserved, however, with wireshark, I can't find any packets sended / received neither on the clients system nor the server system. (I watched port 88 but there is no traffic,...)
Both PCs are connected to one router(D-Link DIR-635) and i guess I would have noticed If multicasting woudl be blocked by the router, right?
What am I missing? Shoudl I try different ports or IPs or could something block the packets? I only use windows firewall and I even turned this thing off for a test.
Here is a running example. I have no problem running this on the same machine but when I run the server on my laptop in the same network, nothing works.
Server
package multicastserver;
import java.net.*;
public class MulticastServer {
public static void main(String[] args) {
int multicastPort = 8888;
try {
InetAddress multicastIP = InetAddress.getByName("228.5.6.7");
InetSocketAddress multicastAddress = new InetSocketAddress( multicastIP, multicastPort );
NetworkInterface multicastInterface = NetworkInterface.getByName( "LAN-Verbindung" );
MulticastSocket multicastSocket = new MulticastSocket( multicastPort );
multicastSocket.joinGroup(multicastAddress, multicastInterface);
int counter = 0;
while(true) {
String message = "This is server, packet nr. " + counter;
counter++;
byte [] buffer = message.getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastIP, multicastPort);
multicastSocket.send(packet);
System.out.println("Sended: " + message);
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println(e);
return;
}
}
}
Client
package multicastclient;
import java.net.*;
public class MulticastClient {
public static void main(String[] args) {
int multicastPort = 8888;
try {
InetAddress multicastIP = InetAddress.getByName("228.5.6.7");
InetSocketAddress multicastAddress = new InetSocketAddress( multicastIP, multicastPort );
NetworkInterface multicastInterface = NetworkInterface.getByName( "LAN-Verbindung" );
MulticastSocket multicastSocket = new MulticastSocket( multicastPort );
multicastSocket.joinGroup(multicastAddress, multicastInterface);
while(true) {
byte [] buffer = new byte[40];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
multicastSocket.receive(packet);
buffer = packet.getData();
String message = new String(buffer, "UTF-8");
System.out.println("Received: " + message);
}
} catch (Exception e) {
System.out.println(e);
return;
}
}
}
I am creating a simple Android app which can communicate with my PC. On my computer I have a very simple UDP server in Java.
public void run(){
try{
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
byte[] sendData = new byte[8];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String sendString = "polo";
sendData = sendString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}catch (Exception e){
}
}
and I have another simple piece of code inside my android app which sends a UDP packet to the server and awaits the response.
public void checkServerOnline(View v) {
try {
int port = 46001;
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(1800);
InetAddress IPAddress = InetAddress.getByName(host);
byte[] sendData = new byte[8];
byte[] receiveData = new byte[8];
String sentence = "marco";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
} catch (Exception e) {
}
The problem I am having is that my Client is timing out waiting for a response. The server is definitely receiving the string "marco" and is presumably sending the response "polo", but the client is not receiving it. I've tried removing the timeout on the client, but it just freezes up until I force close the application.
Can anyone see an error in my code? I can't understand why it won't work. I've managed to successfully setup a TCP Server and client with the same setup, but cannot seem to do UDP.
The server is sending to the wrong port. It should send to the port in the received datagram, not its own port. It is simplest to reuse the request datagram and just change the data to the response data: the return address is already there.
Client A
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientA
{
final private static int PORT = 5005; // arbitrarily assigned port to use
public static void main(String args[]) throws
IOException
{
DatagramSocket socket = new DatagramSocket(PORT); // create new connection on that port
while (true)
{
byte buffer[] = new byte[256]; // data buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // new packet containing buffer
socket.receive(packet); // look for packet
String clientBMsg = new String(packet.getData()); // get data from received packet
InetAddress address = packet.getAddress(); // get address of received packet
System.out.println("ClientB at " + address + " says " + clientBMsg);
buffer = null;
String msgString = "I'm ClientA, vegetables are fun";
buffer = msgString.getBytes(); // put String in buffer
int port = packet.getPort(); // get port of received packet
packet = new DatagramPacket(buffer, buffer.length, address, port); // create new packet with this data
socket.send(packet); // send packet back containing new buffer!
System.out.println("Message Sent");
socket.close();
}
}
}
Client B
import java.io.*;
import java.net.*;
public class ClientB
{
final private static int PORT = 5005; // arbitrarily assigned port - same as server
public static void main(String args[]) throws
IOException {
// if (args.length == 0) { // requires host
// System.err.println
// ("Please specify host");
// System.exit(-1);
// }
// String host = args[0]; // user defined host
DatagramSocket socket = new DatagramSocket(); // open new socket
String host = "localhost";//"86.0.164.207";
byte message[] = new byte[256]; // empty message
String msgString = "Hello, I'm client B and I like trees";
message = msgString.getBytes(); // put String in buffer
InetAddress address = InetAddress.getByName(host); // determines address
System.out.println("Sending to: " + address); // tells user it's doing something
DatagramPacket packet = new DatagramPacket(message, message.length, address, PORT); // create packet to send
socket.send(packet); // send packet
System.out.println("Message Sent");
message = new byte[256];
packet = new DatagramPacket(message, message.length);
socket.receive(packet); // wait for response
String clientAreply = new String(packet.getData());
System.out.println("ClientA at " + host + " says " + clientAreply);
socket.close();
}
}
I don't understand why this works over localhost but when I put my IP address in, it just sends the message and nothing is received.
Can anyone point me in the right direction here?
Thank you!
You should use DatagramSocket's bind method to bind it to your internet interface, otherwise it only listens on 127.0.0.1 or localhost. Like this:
DatagramSocket socket = new DatagramSocket(null);
socket.bind(new InetSocketAddress(InetAddress.getByName("your.ip.add.ress"),5005);
In case you are behind your router then your should listen on the local IP address given to you by the router and use port forwarding to this address in your router settings.
I can suggest using Socket Test tool with TCP and UDP Sockets:
http://sockettest.sourceforge.net/
I used it to trouble shoot issues with a 2-way socket program. You can end-to-end test your link with two SocketTest programs and the compare results, etc. Very useful.
I am trying to program a Java stop-and-wait UDP server and I have gotten this far with the server but I am not sure where to go next. I want the client to send a message to the server, set a timeout, wait for a response, if it doesn't get one, then resend the packet, if it does then increment the sequence no. until it get to ten and keep send and receiving messages with the server.
I have gotten this far, how do I fix this ? :
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws Exception {
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
InetAddress IPAddress = null;
try {
IPAddress = InetAddress.getByName("localhost");
} catch (UnknownHostException exception) {
System.err.println(exception);
}
//Create a datagram socket object
DatagramSocket clientSocket = new DatagramSocket();
while(true) {
String sequenceNo = "0";
sendData = sequenceNo.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
clientSocket.send(sendPacket);
clientSocket.setSoTimeout(1);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
if(clientSocket.receive(receivePacket)==null)
{
clientSocet.send(sendPacket);
}else { //message sent and acknowledgement received
sequenceNo++; //increment sequence no.
//Create a new datagram packet to get the response
String modifiedSentence = sequenceNo;
//Print the data on the screen
System.out.println("From : " + modifiedSentence);
//Close the socket
if(sequenceNo >= 10 ) {
clientSocket.close();
}
}}}}
The first problem I can see (apart from the mistyped variable names which will stop your code compiling) is your socket timeout: if the socket timeout expires, the receive function will throw a SocketTimeoutException which your code does not handle. receive does not return a value, so the result can't be compared with null. Instead, you need to do something like this:
try {
clientSocket.receive(receivePacket);
sequenceNo++;
... // rest of the success path
} catch (SocketTimeoutException ex) {
clientSocket.send(sendPacket);
}