public static void main(String args[]) throws Exception { String serverHostname = args[0]; int portNumber = Integer.parseInt(args[1]); try { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName(serverHostname); System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber); System.out.println("Enter \"Quit\" to exit program"); while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; System.out.print("Enter Message: "); String sentence = inFromUser.readLine(); if (sentence.equals("Quit")) break; sendData = sentence.getBytes(); System.out.println("Sending data to " + sendData.length + " bytes to server."); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, portNumber); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); System.out.println("Waiting for return packet"); clientSocket.setSoTimeout(10000); try { clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); InetAddress returnIPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); System.out.println("From server at: " + returnIPAddress + ":" + port); System.out.println("Message: " + modifiedSentence); } catch (SocketTimeoutException ste) { System.out.println("Timeout Occurred: Packet assumed lost"); } System.out.print("\n"); } clientSocket.close(); } catch (UnknownHostException ex) { System.err.println(ex); } catch (IOException ex) { System.err.println(ex); } }
/** Generic constructor for the name service interface */ public LeetActive(String svc_host, int svc_port, int portNum) { try { nameServer = new DatagramSocket(); nameServer.setSoTimeout(3000); nameServer.connect(InetAddress.getByName(svc_host), svc_port); } catch (Exception e) { System.err.println("LA " + e); } this.portNum = portNum; hostList = new ArrayList(); }
public static void main(String[] args) { try (DatagramSocket socket = new DatagramSocket(0)) { socket.setSoTimeout(10000); InetAddress host = InetAddress.getByName(HOSTNAME); DatagramPacket request = new DatagramPacket(new byte[1], 1, host, PORT); DatagramPacket response = new DatagramPacket(new byte[1024], 1024); socket.send(request); socket.receive(response); String result = new String(response.getData(), 0, response.getLength(), "US-ASCII"); System.out.println(result); } catch (IOException ex) { ex.printStackTrace(); } }
/** * Initialize a new Substrate object. * * @param myIp is the IP address to bind to the socket * @param port is the port number to bind to the socket (may be 0) * @param peerAdr is the IP address/port pair for the peer host (may be null, if this object is * being used in a server) * @param discProb is a discard probability used to randomly discard packets received from the Rdt * object * @param debug is a flag; if it is 1, each packet sent and received is printed out */ Substrate(InetAddress myIp, int port, InetSocketAddress peerAdr, double discProb, boolean debug) { // initialize instance variables this.peerAdr = peerAdr; this.discProb = discProb; this.debug = debug; // open and configure socket with timeout sock = null; try { sock = new DatagramSocket(port, myIp); sock.setSoTimeout(100); } catch (Exception e) { System.out.println("unable to create socket"); System.exit(1); } sndr = new Sender(sock, peerAdr, discProb, debug); rcvr = new Receiver(sock, peerAdr, sndr, debug); }
static byte[] sendReq(byte abyte0[], int i, String s, int j) throws Exception { DatagramSocket datagramsocket = new DatagramSocket(i); try { datagramsocket.setSoTimeout(30000); datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, InetAddress.getByName(s), j)); byte abyte1[] = new byte[512]; DatagramPacket datagrampacket = new DatagramPacket(abyte1, abyte1.length); datagramsocket.receive(datagrampacket); byte abyte2[] = new byte[datagrampacket.getLength()]; System.arraycopy(datagrampacket.getData(), 0, abyte2, 0, datagrampacket.getLength()); datagramsocket.close(); return abyte2; } catch (Exception exception) { try { datagramsocket.close(); } catch (Exception exception1) { } throw exception; } }
static void LoadModule(String s, int i, String s1, boolean flag) { DatagramSocket datagramsocket = null; Object obj = null; System.out.println("Loading from " + s + ":" + i); try { datagramsocket = new DatagramSocket(); datagramsocket.setSoTimeout(10000); InetAddress inetaddress = InetAddress.getByName(s); Module module = LoadModule(datagramsocket, inetaddress, i, s1, flag); if (module != null) module.write(); } catch (Exception exception) { exception.printStackTrace(); if (datagramsocket != null) try { datagramsocket.close(); } catch (Exception exception2) { } return; } try { datagramsocket.close(); } catch (Exception exception1) { } }
public static void main(String[] args) { // Checks if no command line args were given by usej if (args.length <= 0) { System.out.println("No user specified!"); return; } // Sets the filename equal to the command line argument String filename = ""; String message = args[0]; try { // Creates an InetAddress using localhost InetAddress address = InetAddress.getByName("localhost"); // The byte buffer used for data the client is sending byte[] sdata = new byte[PACKET_SIZE]; // The byte buffer used for data the client is receiving byte[] rData = new byte[PACKET_SIZE]; // Puts "Sync" into the send Data sdata = ("SYNC" + message).getBytes(); DatagramSocket socket = new DatagramSocket(); // Socket timesout after 5 seconds to prevent infinite wait socket.setSoTimeout(5000); // Creates the packet and puts in the message DatagramPacket packet = new DatagramPacket(sdata, sdata.length, address, 3031); // Sends packet with the message to the server socket.send(packet); // Creates the recieve packet DatagramPacket rpacket = new DatagramPacket(rData, rData.length); socket.receive(rpacket); // Pulls the string out of the recieved packet String cmd1 = new String(rpacket.getData(), 0, rpacket.getLength()); // Checks if the server sent SYNACK if (cmd1.substring(0, 6).equals("SYNACK")) { String dirList = cmd1.substring(6); System.out.println(dirList); System.out.flush(); System.out.println( "Please type the file you wish to receive, or type " + "EXIT to close the server"); Scanner scan = new Scanner(System.in); filename = scan.next(); // Puts the file named into the Send Data sdata = filename.getBytes(); // Creates a Packet with the Filename packet = new DatagramPacket(sdata, sdata.length, address, 3031); socket.send(packet); } else return; // Checks if the filename is Exit. If so the client exits as well if (filename.equals("EXIT")) { System.out.println("Exit request sent."); return; } // Creates a local file to put the data recieved from the server in. socket.receive(rpacket); // Pulls the filename out of the recieved packet filename = new String(rpacket.getData(), 0, rpacket.getLength()); // Check if the first 7 characters are 'FILEACK', if so set file name // to the rest of the message if (filename.substring(0, 7).equals("FILEACK")) { filename = filename.substring(9 + message.length(), filename.length()); System.out.println("File name requested: " + filename); } else { // If no FILEACK, then the file specified was not valid System.out.println("Not a valid file!"); return; } File file = new File("local_" + filename); // Opens a FileOutputStream to use to write the data in the above file. FileOutputStream fos = new FileOutputStream(file); // Creates the receiving packet for data comming form the server System.out.println("Transfer started."); // The loop to received the packets of requested data. windowPackets = new DatagramPacket[MAX_SEQ]; CRC32 crc = new CRC32(); while (!done) { // Receives a packet sent from server socket.receive(rpacket); // Initialize arrays byte[] info = new byte[INT_SIZE]; byte[] code = new byte[CHECKSUM_SIZE]; byte[] data = new byte[rpacket.getLength() - SAC_SIZE]; byte[] data2 = new byte[rpacket.getLength() - CHECKSUM_SIZE]; // Split packet data into appropriate arrays System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); System.arraycopy(rpacket.getData(), INT_SIZE, data, 0, rpacket.getLength() - SAC_SIZE); System.arraycopy(rpacket.getData(), 0, data2, 0, rpacket.getLength() - CHECKSUM_SIZE); System.arraycopy( rpacket.getData(), rpacket.getLength() - CHECKSUM_SIZE, code, 0, CHECKSUM_SIZE); // Convert seq num and other numbers from bytes to ints int packNum2 = ByteConverter.toInt(info, 0); int sCode = ByteConverter.toInt(code, 0); int packNum = ByteConverter.toInt(info, 0); // Reset and update crc for next packet crc.reset(); crc.update(data2, 0, data2.length); int cCode = (int) crc.getValue(); byte[] ackNum = ByteConverter.toBytes(packNum); ArrayList<Integer> expecting = new ArrayList<Integer>(); // Check for errors if (cCode == sCode) { // Create expected sequence numbers for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If packet number is base packet number if (packNum == base) { ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); // If last packet if (rpacket.getLength() == 0) { done = true; break; } // Write and move base forward fos.write(data, 0, data.length); base++; if (base == MAX_SEQ) base = 0; // update expected packets for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If the packet has data it writes it into the local file. // If this packet is smaller than the agree upon size then it knows // that the transfer is complete and client ends. if (rpacket.getLength() < PACKET_SIZE) { System.out.println("File transferred"); done = true; break; } // While there are packets in buffer, move packet to file while (windowPackets[base] != null) { DatagramPacket nextPacket = windowPackets[base]; windowPackets[base] = null; data = new byte[nextPacket.getLength() - SAC_SIZE]; System.arraycopy( nextPacket.getData(), INT_SIZE, data, 0, nextPacket.getLength() - SAC_SIZE); System.arraycopy(nextPacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); // If packet size is 0, then it is the last packet if (nextPacket.getLength() == 0) { System.out.println("File transferred"); done = true; break; } // Write and move base forward fos.write(data, 0, data.length); base++; if (base == MAX_SEQ) base = 0; expecting.clear(); // Update expected for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If the packet has data it writes it into the local file. // If this packet is smaller than the agree upon size then it knows // that the transfer is complete and client ends. if (nextPacket.getLength() < PACKET_SIZE) { System.out.println("File transferred"); done = true; break; } } } else if (expecting.contains(packNum)) { // If its expected, put it into buffer windowPackets[packNum] = rpacket; System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); } else { // If not expected, just ACK packet System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); } } else { // CRC found error with packet System.out.println("ERROR"); } } // transfer is done System.out.println("File length - " + file.length()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String args[]) throws Exception { int index; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; // Pull the target host from the command line. InetAddress ipAddress = null; if (args.length > 0) { ipAddress = InetAddress.getByName(args[0]); } else { System.err.println("FATAL: You must specify a hast to connect to."); System.exit(1); } // Get the request string from input and send it off. String request = inFromUser.readLine(); sendData = request.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, PORT); clientSocket.send(sendPacket); // Get the header packet. DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); receiveData = receivePacket.getData(); String[] words = new String[8]; words = (new String(receiveData)).split("\\s+"); int numBytes = Integer.parseInt(words[1]); boolean[] packets = new boolean[numBytes]; File download_file = new File("downloaded_file"); download_file.createNewFile(); RandomAccessFile download = new RandomAccessFile(download_file, "rw"); download.setLength(numBytes); clientSocket.setSoTimeout(1000); // Get the server's response. do { try { while (true) { receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); receiveData = receivePacket.getData(); // Convert the first two bytes back into the integer index of this packet. index = 256 * (receiveData[0] & 0xff) + (receiveData[1] & 0xff); packets[index] = true; download.seek(index * 1022); for (int i = 0; i < 1021; ++i) { download.writeByte(receiveData[i + 2]); } } } catch (Exception e) { } } while (moreToDo(packets)); }
public static void main(String[] args) throws Exception { //////////////////// STAGE A////////////////////////////////////////// int portNum = 12235; // InetAddress ip=InetAddress.getLocalHost(); InetAddress ip = InetAddress.getByName("attu2.cs.washington.edu"); DatagramSocket sock = new DatagramSocket(); byte[] response = new byte[HEADER_SIZE + 16]; String partA = "hello world\0"; byte[] buf = createBuffer(partA.getBytes(), 0, STEP1); DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, portNum); sock.send(packet); packet = new DatagramPacket(response, response.length); sock.receive(packet); int[] a2 = partA(response); // putting the 4 ints from server into int[] // for (int i = 0; i < a2.length; i++) { // System.out.println(a2[i]); // } ////////////////////// STAGE B//////////////////////////////////////// int numSent = 0; int send = a2[0]; int len = a2[1]; portNum = a2[2]; int secretA = a2[3]; System.out.println("The secrets:\nA: " + secretA); sock.setSoTimeout(500); // .5s while (numSent < send) { // create packet buf = createBuffer(partB(numSent, len), secretA, STEP1); packet = new DatagramPacket(buf, buf.length, ip, portNum); sock.send(packet); // send packet try { sock.receive(new DatagramPacket(response, response.length)); numSent++; ByteBuffer temp = ByteBuffer.wrap(response); checkHeader(temp, 4, secretA, STEP1); // System.out.println(temp.getInt()); // For debug. See if counts up by 1 } catch (SocketTimeoutException e) { // if there's a timeout, try again continue; } } response = new byte[HEADER_SIZE + 8]; // 8 bytes -- 2 integers sock.receive(new DatagramPacket(response, response.length)); ByteBuffer bb = ByteBuffer.wrap(response); // Header checkHeader(bb, 8, secretA, STEP2); // reset the port number to the one given portNum = bb.getInt(); int secretB = bb.getInt(); System.out.println("B: " + secretB); // close the UDP socket sock.close(); /////////////////////////// STAGE C/////////////////////////////////// Socket socket = new Socket(ip, portNum); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); response = new byte[HEADER_SIZE + 16]; // 4 ints given to us this time in.read(response); bb = ByteBuffer.wrap(response); // Header checkHeader(bb, 13, secretB, STEP2); // num2 len2 secretC and char c numSent = bb.getInt(); len = bb.getInt(); int secretC = bb.getInt(); System.out.println("C: " + secretC); // stage d byte c = (byte) bb.getChar(); buf = new byte[len]; Arrays.fill(buf, c); for (int i = 0; i < numSent; i++) { byte[] b = createBuffer(buf, secretC, STEP1); out.write(b); } response = new byte[12 + 4]; // one integer. secretD plus header in.read(response); bb = ByteBuffer.wrap(response); checkHeader(bb, 4, secretC, STEP2); int secretD = bb.getInt(); socket.close(); in.close(); out.close(); System.out.println("D: " + secretD); }
public static void main(String args[]) throws Exception { DatagramSocket r_clients = null, s_clients = null; MulticastSocket servers = null, b_clients = null; local = Integer.parseInt(args[1]); rec = Integer.parseInt(args[0]); System.out.println("Recieving arp on port " + rec + "..."); System.out.println("Recieving reply arp on port " + (rec + 1) + "..."); System.out.println("\nEmulating gateway on port " + local + "\nWaiting..."); try { r_clients = new DatagramSocket(rec); s_clients = new DatagramSocket(rec + 1); b_clients = new MulticastSocket(local); b_clients.joinGroup(InetAddress.getByName(group)); servers = new MulticastSocket(serv_port); servers.joinGroup(InetAddress.getByName(group)); servers.setSoTimeout(10); s_clients.setSoTimeout(10); b_clients.setSoTimeout(10); r_clients.setSoTimeout(10); } catch (Exception e) { System.out.println("error: " + e.toString()); System.exit(1); } byte arp_buf[] = new byte[28]; DatagramPacket arp_packet = new DatagramPacket(arp_buf, arp_buf.length); while (true) { try { servers.receive(arp_packet); System.out.println("\nGot arp from servers"); System.out.println("Sending arp to local computers"); arp_packet.setAddress(InetAddress.getByName(group)); arp_packet.setPort(local); try { b_clients.send(arp_packet, (byte) 255); } catch (Exception e3) { } } catch (Exception e) { try { r_clients.receive(arp_packet); System.out.println("\nGot arp from client"); System.out.println("Sending ARP"); arp_packet.setAddress(InetAddress.getByName(group)); arp_packet.setPort(serv_port); try { servers.send(arp_packet, (byte) 255); } catch (Exception e3) { } } catch (Exception e2) { try { s_clients.receive(arp_packet); System.out.println("\nGot reply arp from client"); arp_packet.setAddress(InetAddress.getByName(group)); arp_packet.setPort(2500); try { s_clients.send(arp_packet); } catch (Exception e3) { } } catch (Exception e4) { } } } } }