java.net.BindException: EADDRINUSE (Address already in use) - java

I'm trying to connect and transfer data through Wifi-Direct on Android phones. What I've basically done in my P2PConnectionManager.java file is -
Created a connection to the peer through the P2pManager
Called the class ServerHandshake if I am the Group Owner
Called the class ClientHandshake if I am not the GroupOwner
in these two classes I have exchanged the IP addresses and MAC addresses of the phones (this I've done to enable communication with multiple phones). I have used Datagram Sockets everywhere as that is what is required right now for what I am trying to do.
In P2PSend.java, once I select the file, I have tried to send it over a DatagramSocket as well, but it is giving me a bind failed: EADDRINUSE (Address already in use) exception.
I am using different ports for both the connections, and even included socket.setReuseAddress()
Can someone please point out where I am going wrong? I apologize for the mess in the code.
P2PConnectionManager.java:
public void onConnectionInfoAvailable(WifiP2pInfo info) {
//here check whether we're the group owner, then create server socket if so
if(info.isGroupOwner){
appendToConsole("CMGR: Setting up server handshake on " + info.groupOwnerAddress.getHostAddress() + ":5555");
//setup the server handshake with the group's IP, port, the device's mac, and the port for the conenction to communicate on
ServerHandshake sh = new ServerHandshake();
sh.setup(myMAC, info.groupOwnerAddress.getHostAddress(),5555,childportstart);
childportstart += 2;
sh.execute();
}else{
//give server a second to setup the server socket
try{
Thread.sleep(1000);
}catch (Exception e){
System.out.println(e.toString());
}
String myIP = "";
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()){
NetworkInterface ni = en.nextElement();
Enumeration<InetAddress> en2 = ni.getInetAddresses();
while(en2.hasMoreElements()){
InetAddress inet = en2.nextElement();
if(!inet.isLoopbackAddress() && inet instanceof Inet4Address){
myIP = inet.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
appendToConsole("CMGR: Setting up client handshake from " + myIP + ":5555");
//setup the client handshake to connect to the server and trasfer the device's MAC, get port for connection's communication
ClientHandshake ch = new ClientHandshake();
ch.setup(info.groupOwnerAddress.getHostAddress(),5555,myMAC,myIP);
ch.execute();
}
}
ClientHandshake class:
public class ClientHandshake extends AsyncTask<Void, Void, String> {
String peerIP;
String peerMAC;
int peerPort;
int childport;
byte[] buffer;
byte[] buffer2;
DatagramSocket clientSocket;
OutputStream outs;
InputStream ins;
String myMAC;
String myIP;
public void setup(String peerIP, int peerPort, String myMAC, String myIP ) {
this.peerIP = peerIP;
this.peerPort = peerPort;
this.myMAC = myMAC;
this.myIP = myIP;
}
public String doInBackground(Void...params) {
try{
clientSocket = new DatagramSocket(peerPort);
clientSocket.setReuseAddress(true);
System.out.println("Peerport: " + peerPort);
InetAddress IPAddress = InetAddress.getByName(peerIP);
System.out.println("CH: PEERIP ADDRESS - " + IPAddress);
int len = myIP.length();
byte[] sendMyMac = new byte[17];
byte[] sendMyIPlen = new byte[2];
byte[] sendMyIP = new byte[len];
byte[] receivePeerMAC = new byte[17];
byte[] receivePort = new byte[4];
//write our MAC address
sendMyMac = myMAC.getBytes();
System.out.println("myMAC - " + myMAC);
DatagramPacket sendPacket1 = new DatagramPacket(sendMyMac, sendMyMac.length, IPAddress, peerPort);
clientSocket.send(sendPacket1);
System.out.println("sendMyMAC done -");
//write our IP add len
String string = String.valueOf(myIP.length());
sendMyIPlen = string.getBytes();
System.out.println("myIPlen - " + myIP.length());
DatagramPacket sendPacket2 = new DatagramPacket(sendMyIPlen, sendMyIPlen.length, IPAddress, peerPort);
clientSocket.send(sendPacket2);
System.out.println("sendMyIPlen done -");
//write our IP add
sendMyIP = myIP.getBytes();
System.out.println("myIP - " + myIP);
DatagramPacket sendPacket3 = new DatagramPacket(sendMyIP, sendMyIP.length, IPAddress, peerPort);
clientSocket.send(sendPacket3);
System.out.println("SendMyIP done -");
//read peer's MAC address
DatagramPacket receivePeerMac = new DatagramPacket(receivePeerMAC, receivePeerMAC.length);
clientSocket.receive(receivePeerMac);
String peerMAC = new String(receivePeerMac.getData());
System.out.println("FROM SERVER:" + peerMAC);
//read the port
DatagramPacket port = new DatagramPacket(receivePort, receivePort.length);
clientSocket.receive(port);
String cport = new String (port.getData());
int childport = Integer.parseInt(cport);
clientSocket.close();
return peerMAC;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String peerMAC){
createNewP2PConnection(myMAC,myIP,peerMAC,peerIP,childport,0);
}
}
ServerHandshake class:
public class ServerHandshake extends AsyncTask<Void, Void, String> {
int portno;
int childport;
int peerIPlen;
byte[] buffer;
byte[] buffer2;
Socket s;
DatagramSocket serverSocket;
InputStream ins;
OutputStream outs;
String myMAC;
String myIP;
String ipaddr;
String peerMAC;
String peerIP;
int myPort;
public void setup(String myMAC, String myIP, int myPort, int childport) {
this.myIP = myIP;
this.myMAC = myMAC;
this.myPort = myPort;
this.childport = childport;
}
public String doInBackground(Void...params) {
System.out.println("Checking SH");
System.out.println("CP : "+childport);
try{
serverSocket = new DatagramSocket(5555);
serverSocket.setReuseAddress(true);
//serverSocket.setSoTimeout(5000);
byte[] receivePeerMAC = new byte[17];
byte[] receivePeerIPlen = new byte[2];
byte[] sendMyMac = new byte[17];
byte[] sendMyPort = new byte[4];
try {
Thread.sleep(5000);
}catch(Exception e) {
e.printStackTrace();
}
//read Peer Mac
DatagramPacket PeerMac = new DatagramPacket(receivePeerMAC, receivePeerMAC.length);
serverSocket.receive(PeerMac);
String peerMAC = new String(PeerMac.getData());
System.out.println("RECEIVEDpeerMAC: " + peerMAC);
InetAddress IPAddress = PeerMac.getAddress();
int port = PeerMac.getPort();
//read peer IP's len
DatagramPacket IPlen = new DatagramPacket(receivePeerIPlen, receivePeerIPlen.length);
serverSocket.receive(IPlen);
String PeerIPlen = new String(IPlen.getData());
int peerIPlen = Integer.parseInt(PeerIPlen);
System.out.println("RECEIVEDpeerIPlenstring: " + PeerIPlen + " .... int: " + peerIPlen + "ANY DIFFERENCE??");
//read peer IP
byte [] receivePeerIP = new byte [peerIPlen];
DatagramPacket IP = new DatagramPacket(receivePeerIP, receivePeerIP.length);
serverSocket.receive(IP);
String peerIP = new String(IP.getData());
System.out.println("RECEIVEDpeerIP: " + peerIP);
//Write our local MAC
sendMyMac = myMAC.getBytes();
System.out.println("myMAC - " + myMAC);
DatagramPacket sendPacket1 = new DatagramPacket(sendMyMac, sendMyMac.length, IPAddress, port);
serverSocket.send(sendPacket1);
System.out.println("sendMyMAC done -");
//Write the port to talk on
String string = String.valueOf(childport);
sendMyPort = string.getBytes();
DatagramPacket sendPacket2 = new DatagramPacket(sendMyPort, sendMyPort.length, IPAddress, port);
serverSocket.send(sendPacket2);
System.out.println("Port: " + childport);
serverSocket.close();
return (peerIP);
}catch(Exception e){
e.printStackTrace();
}
return (null);
}
public void onPostExecute(String peerIP){ //changed from (String peerMAC)
createNewP2PConnection(myMAC,myIP,peerMAC,peerIP,childport,1);
}
}
P2PSend.java:
Note: I have used IntentService here, just to get the filepath, destination IP and port
public class P2PSend extends IntentService {
private static final int SOCKET_TIMEOUT = 15000;
public static final String ACTION_SEND_FILE = "com.p2pwifidirect.connectionmanager.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_DESTINATION = "go_host";
public static final String EXTRAS_DESTINATION_PORT = "go_port";
public static final String EXTRAS_MY_IP = "my_ip";
public P2PSend() {
super("P2PSend");
System.out.println("P2PSend.java started IntentService");
}
protected void onHandleIntent(Intent intent) {
System.out.println("P2PSend.java started onHandleIntent");
Context context = getApplicationContext();
System.out.println("Intent: " + intent);
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_DESTINATION); //this is the IP address of the receiver
String myIP = intent.getExtras().getString(EXTRAS_MY_IP); //my IP address
System.out.println("P2PSend:Host Address: " + host);
//int port = intent.getExtras().getInt(EXTRAS_DESTINATION_PORT);
int port = 6000;
System.out.println("P2PSend:Port: " + port);
System.out.println("P2PSend:fileUri: " + fileUri);
try {
DatagramSocket socket = new DatagramSocket(port);
System.out.println("Opening client socket - ");
//socket.bind(new InetSocketAddress(myIP, port));
InetAddress hostAddress = InetAddress.getByName(host);
socket.connect(new InetSocketAddress(hostAddress, port));
//socket.setSoTimeout(SOCKET_TIMEOUT); //is it needed???
System.out.println("Client socket - " + socket.isConnected());
ContentResolver cr = context.getContentResolver();
InputStream is = null;
is = cr.openInputStream(Uri.parse(fileUri));
byte buf[] = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
DatagramPacket packet = new DatagramPacket(buf,buf.length, hostAddress, port);
//System.out.println("Client socket - " + socket.isConnected());
socket.send(packet);
System.out.println("Writing data: " + packet);
System.out.println("Writing data now...");
}
is.close();
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Client: Data written");
}
Any suggestions as to where I'm going wrong?
Thank you so much!

Create the socket this way:
clientSocket = new DatagramSocket();
clientSocket.setReuseAddress(true);
clientSocket.bind(new InetSocketAddress(peerPort));
If you want to send Broadcast, also consider adding this line before binding it:
clientSocket.setBroadcast(true);

Related

How to group 2 udp clients?

What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i don't know how to make it work like described above. Messages are send from client by typing something in console.
server:
public class Server extends Thread{
public final static int PORT = 7331;
private final static int BUFFER = 1024;
private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;
public Server() throws IOException {
socket = new DatagramSocket(PORT);
System.out.println("[SERVER] UDP server successfully launched on port " + PORT);
clientAddresses = new ArrayList<InetAddress>();
clientPorts = new ArrayList<Integer>();
existingClients = new HashSet<String>();
}
public void run() {
byte[] buf = new byte[BUFFER];
while (true) {
try {
//resets buffer so only new messages get displayed
Arrays.fill(buf, (byte) 0);
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String content = new String(buf, buf.length);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
String id = clientAddress.toString() + "," + clientPort;
if (!existingClients.contains(id)) {
existingClients.add(id);
clientPorts.add(clientPort);
clientAddresses.add(clientAddress);
}
System.out.println(id + " : " + content);
byte[] data = (id + " : " + content).getBytes();
for (int i = 0; i < clientAddresses.size(); i++) {
InetAddress cl = clientAddresses.get(i);
int cp = clientPorts.get(i);
packet = new DatagramPacket(data, data.length, cl, cp);
socket.send(packet);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
public static void main(String args[]) throws Exception {
Server s = new Server();
s.start();
}
}
clients:
public class Client implements Runnable {
public static void main(String args[]) throws Exception {
String host = "127.0.0.1";
DatagramSocket socket = new DatagramSocket();
//handles the receiving part for every client (incoming packets to clients)
MessageReceiver r = new MessageReceiver(socket);
Client s = new Client(socket, host);
Thread rt = new Thread(r);
Thread st = new Thread(s);
rt.start();
st.start();
}
public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;
Client(DatagramSocket s, String h) {
sock = s;
hostname = h;
}
//sending clients socket to server
private void sendMessage(String s) throws Exception {
//getting bytes from message
byte buf[] = s.getBytes();
//getting hostname from server
InetAddress address = InetAddress.getByName(hostname);
//setting up packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
//sending packet to server
sock.send(packet);
}
public void run() {
//connected boolean is used to send a greetings message once for every new client that has joined
boolean connected = false;
do {
try {
sendMessage("GREETINGS");
connected = true;
} catch (Exception e) {
}
} while (!connected);
//reads from the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
while (!in.ready()) {
Thread.sleep(100);
}
//sends message from console to server
sendMessage(in.readLine());
} catch (Exception e) {
System.err.println(e);
}
}
}
}
//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];
MessageReceiver(DatagramSocket s) {
sock = s;
buf = new byte[1024];
}
public void run() {
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
sock.receive(packet);
String received = new String(packet.getData(), 0,
packet.getLength());
System.out.println(received);
} catch (Exception e) {
System.err.println(e);
}
}
}
}
What youre trying is a message broadcast or a message-repeater-client.
broadcasting is implemented on network layer (using brodcast the local network broadcast adress).
And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)

How to make a asnychron REST Server with communication to external hardware

I am currently working on a REST server in Spring Boot that also communicates with external hardware via USB or TCP/IP. A command is sent to the external device, then I wait 2 seconds for the response and return it to the RestController.
For the USB communication I am currently using jSerialComm. For the TCP/IP communication I use sockets.
The whole thing also works so far when I use Thread.sleep. However, I would prefer it to be more dynamic, i.e. without the sleep, because TCP/IP can cause delays.
For me Java and REST are still new. Is there a way to let the server communicate asynchronously with the hardware?
#RestController
#RequestMapping("/api/v1")
public class CommController {
#GetMapping("/Version")
public String getVersion() {
Serial serial = new Serial();
String s_response = null;
s_response = serial.getVersion();
return s_response;
}
#GetMapping("/VersionTCPIP")
public String getVersionTCPIP() {
Serial serial = new Serial();
String s_response = null;
s_response = serial.getVersionTCPIP();
return s_response;
}
}
USB/serial-class:
public class Serial {
private static SerialPort port;
private static List<Byte> l_readBuffer;
private static final class MessageListener implements SerialPortDataListener
{
#Override
public int getListeningEvents()
{
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
#Override
public void serialEvent(SerialPortEvent event)
{
if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
return;
byte[] newData = new byte[port.bytesAvailable()];
int numRead = port.readBytes(newData, newData.length);
for (int i = 0; i < numRead; i++)
{
l_readBuffer.add(newData[i]);
}
System.out.println("Read " + numRead + " bytes.");
}
}
public String getVersion() {
SerialPort[] ports = SerialPort.getCommPorts();
port = null;
for (SerialPort currentPort :
ports)
{
if (currentPort.getDescriptivePortName().contains("XXX"))
{
port = currentPort;
break;
}
}
Objects.requireNonNull(port).setBaudRate(9600);
port.setParity(SerialPort.NO_PARITY);
port.setNumStopBits(SerialPort.ONE_STOP_BIT);
port.setNumDataBits(8);
port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
//port.clearRTS();
port.setComPortTimeouts(SerialPort.LISTENING_EVENT_DATA_AVAILABLE, 5000, 5000);
port.openPort();
MessageListener listener = new MessageListener();
port.addDataListener(listener);
l_readBuffer = new ArrayList<>();
byte[] sendBuffer = new byte[5];
// fill sendBuffer
port.writeBytes(sendBuffer, sendBuffer.length);
try
{
Thread.sleep(2000);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Data raw: " + l_readBuffer.toString());
byte[] ba_responseBuffer = new byte[l_readBuffer.size()];
for (int i = 0; i < l_readBuffer.size(); i++)
{
ba_responseBuffer[i] = l_readBuffer.get(i);
}
String s_version = new String(ba_responseBuffer);
System.out.println("Version: " + s_version);
port.removeDataListener();
port.closePort();
return s_version;
}
public String getVersionTCPIP()
{
Socket socket;
String s_versionString = null;
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(s_hostnameTCPIP, i_port), 1000);
byte[] ba_sendBuffer = new byte[1024];
Arrays.fill(ba_sendBuffer, (byte) 0x00);
// fill sendBuffer
// send data
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.write(ba_sendBuffer); // write the message
dOut.writeInt(i_sendLength); // write length of the message
dOut.flush();
try
{
Thread.sleep(2000);
} catch (Exception e)
{
e.printStackTrace();
}
byte[] ba_responseBuffer = new byte[0];
if (socket.isConnected())
{
try
{
InputStream inFromServer = socket.getInputStream();
DataInputStream dIn = new DataInputStream(inFromServer);
synchronized (dIn)
{
int length = dIn.available();
ba_responseBuffer = new byte[length];
// receive data
dIn.readFully(ba_responseBuffer);
}
} catch (IOException ex)
{
ex.printStackTrace();
}
String s_version = new String(ba_responseBuffer);
System.out.println("Version: " + s_version);
s_versionString = s_version;
socket.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
return s_versionString;
}
}

Java DatagramSocket doesn't receive data

I'm writing a simple client / server in java and I got this problem that I cannot fix.
I'm using DatagramSocket on both client and server and my server just cannot receive any data. I don't get any errors but it just doesn't work.
Here is my source code for server:
public class GameServer {
public static final String serverBuild = "0.00 (050319.milestone0-main)";
public static final String protocolBuild = "1";
public DatagramSocket serverSocket;
public boolean isRunning = false;
public Thread clientHandler;
public GameServer(int port, String serverName) {
System.out.println("Server> Starting a server on port: " + port + ".");
System.out.println("Server> " + serverName + " running on server build " + serverBuild + ".");
System.out.println("Server> Using protocol ID: " + protocolBuild + ".");
isRunning = true;
try {
serverSocket = new DatagramSocket(port);
}catch(Exception ex) {
System.out.print("Server> ");
ex.printStackTrace();
}
clientHandler();
}
public void clientHandler() {
clientHandler = new Thread(new Runnable() {
public void run() {
while(isRunning) {
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
serverSocket.receive(packet);
System.out.println("Server> " + new String(packet.getData(), 0, packet.getData().length));
} catch (IOException e) {
System.out.print("Server> ");
e.printStackTrace();
}
}
}
});
clientHandler.start();
}
}
Here is my source code for client:
public class GameClient {
public GameClient() {
try {
DatagramSocket socket = new DatagramSocket(25567);
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.0.24"), 25567);
socket.send(packet);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
Client is very simple because I was looking why my server doesn't work.
The console does not print anything, because the client sends the package is an empty array. The server is work right.

DatagramSocket will randomly stop receiving packets (still receives sometimes)

I am trying to implement a TFTP client in Java. The client works perfectly on Localhost and will sometimes work sending to a TFTP server over the network. However, sometimes my DatagramSocket will randomly stop receiving packets. It will send a read/write request but it never receives the next message the server tries to send back. I've checked Wireshark, and the server is for sure receiving and trying to send. And firewalls are turned off where the need to be. Can't figure out what the problem is. Here is the code I am using:
public class TFTPClient {
String filename;
String mode;
boolean read;
PacketBuilder builder;
String IP;
JFrame frame;
public TFTPClient(String uifilename, String uimode, boolean uiread, String uiIP, JFrame uiFrame){
this.filename = uifilename;
this.read = uiread;
this.mode = uimode;
this.IP = uiIP;
builder = new PacketBuilder();
this.frame = uiFrame;
}
/*
* Method choses between reading a file and writing a file based on boolean selected in main UI.
*/
public void startTFTP() throws IOException{
if (read){
readFile();
}
else{
writeFile();
}
}
/*
* Method is used for writing a file
*/
private void writeFile() throws IOException{
byte[] WRQ = builder.getWRQ(filename,mode);
String filenameAndExtension = filename;
RandomAccessFile f = new RandomAccessFile(filenameAndExtension, "r");
byte[] fileBytes = new byte[(int)f.length()];
f.read(fileBytes);
f.close();
DatagramSocket TFTPSocket = new DatagramSocket();
TFTPSocket.setSoTimeout(5000);
//create the packet and send to port 69 of the given IP
DatagramPacket wrqPacket = new DatagramPacket(WRQ, WRQ.length,
InetAddress.getByName(IP), 69);
try {
TFTPSocket.send(wrqPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
byte[] ackByte = new byte[4];
DatagramPacket ackPacket = new DatagramPacket(ackByte,
ackByte.length);
int blockNumber = 0;
DatagramPacket dataPacket;
boolean terminateOnNextAck = false;
boolean needExtraDataPacket = false;
int currentIndex = 0;
while(true)
{
TFTPSocket.receive(ackPacket);
System.out.println("Server acked " + ackByte[3]);
System.out.println("Expected ack " + blockNumber);
blockNumber++;
if(terminateOnNextAck){
break;
}
byte[]DATAdata;
if (needExtraDataPacket){
DATAdata = new byte[0];
terminateOnNextAck = true;
}
else if (currentIndex + 512 > fileBytes.length){
//This is our last byte. Length will be smaller than 508
DATAdata = new byte [fileBytes.length - currentIndex];
terminateOnNextAck = true;
}
else{
DATAdata = new byte[512];
}
if (currentIndex + 512 ==fileBytes.length){
needExtraDataPacket = true;
}
for (int i = 0; i<DATAdata.length; i++){
DATAdata[i] = fileBytes[currentIndex];
currentIndex++;
}
byte[] DATA = builder.getData(DATAdata, blockNumber);
dataPacket = new DatagramPacket(DATA, DATA.length,
InetAddress.getByName(IP),ackPacket.getPort());
try {
TFTPSocket.send(dataPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
TFTPSocket.close();
System.out.println("Write sucessful");
}
/*
* Method is used for reading a file
*/
private void readFile() throws IOException{
//Get RRQ packet
byte[] RRQ = builder.getRRQ(filename,mode);
StringBuffer fileText = new StringBuffer();
DatagramSocket TFTPSocket = new DatagramSocket();
TFTPSocket.setSoTimeout(5000);
//create the packet and send to port 69 of the given IP
DatagramPacket rrqPacket = new DatagramPacket(RRQ, RRQ.length,
InetAddress.getByName(IP), 69);
try {
TFTPSocket.send(rrqPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
byte[] dataByte = new byte[516];
for (int i = 516;i<516;i++){
dataByte[i] = 0;
}
DatagramPacket dataPacket = new DatagramPacket(dataByte,
dataByte.length);
System.out.println("Client: Waiting for packet.");
DatagramPacket ackPacket;
boolean error = false;
while(true)
{
TFTPSocket.receive(dataPacket);
System.out.println(TFTPSocket.getLocalPort());
if (dataByte[1] == 5){
error = true;
break;
}
fileText.append(new String(dataPacket.getData(),0,dataPacket.getLength()));
byte blockNumbers[] = new byte[2];
blockNumbers[0] = dataByte[2];
blockNumbers[1] = dataByte[3];
byte[] ACK = builder.getACK(blockNumbers);
ackPacket = new DatagramPacket(ACK, ACK.length,
InetAddress.getByName(IP),dataPacket.getPort());
try {
TFTPSocket.send(ackPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
if (dataByte[515] == 0){
break;
}
dataByte[515] = 0;
}
if (!error){
JOptionPane.showMessageDialog(frame, "Read Successful!");
System.out.println(fileText);
}
else{
JOptionPane.showMessageDialog(frame,"Error from server: " + new String(dataPacket.getData(),0,dataPacket.getLength()));
}
}
}
The issue turned out to be something with Mac OS X. The program runs fine on Windows. Not entirely sure why, though.

unknown host exception when I try to send request

I'm trying to check whether several pors are open and if 80 port is open - send http request and then show result in console. Every port is checked in his own thread.
I send requests like this
public static void send(Socket sock, String host) throws IOException{
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: " + host);
pw.println("");
pw.flush();
}
In class TCPClient I use it and return result as bytes and then show it console.
try {
sock = new Socket(host, port);
System.out.println("port " + port + " is in use");
// send request
HttpSender.send(sock, host);
BufferedReader bf = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer response = new StringBuffer();
String line = "";
while((line = bf.readLine()) != null) {
response.append(line);
response.append('\r');
}
bf.close();
return String.valueOf(response).getBytes(); // in method run I show it
} catch (SocketException e) {
return ("port " + port + " is free").getBytes();
}
I create pool of threads for port checking.
public class ThreadPool {
private static int MAX_THREADS = 5;
private static String DESTINATION = "http://stackoverflow.com/";
private ExecutorService es = null;
public ThreadPool() {
es = Executors.newFixedThreadPool(MAX_THREADS);
}
public void perform(int start, int end) throws UnknownHostException {
for (int i = start; i <= end; i++) {
Runnable req = new TCPClient(DESTINATION, i);
es.execute(req);
}
es.shutdown();
while (!es.isTerminated()) {
}
;
System.out.println("all ports checked!");
}
}
When I set destination as www.stackoverflow.com and got document with text that it was moved permanently to http://stackoverflow.com/. When I set this destination - I've got UnknownhostException.
Where is the problem?
Have you tried private static String DESTINATION = "stackoverflow.com";? The string "http://stackoverflow.com" isn't a hostname, it's a URL.

Categories