/** Creates the server. */ public static void main(String args[]) { client = null; ServerSocket server = null; try { System.out.print("\nCreating Server...\n"); // creates the server server = new ServerSocket(8008); System.out.print("Created\n"); // get the ip Address and the host name. InetAddress localAddr = InetAddress.getLocalHost(); System.out.println("IP address: " + localAddr.getHostAddress()); System.out.println("Hostname: " + localAddr.getHostName()); } catch (IOException e) { // sends a System.out.println("IO" + e); } // constantly checks for a new aocket trying to attach itself to the trhead while (true) { try { client = server.accept(); // create a new thread. FinalMultiThread thr = new FinalMultiThread(client); System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n"); CliList.add(thr); current++; thr.start(); } catch (IOException e) { System.out.println(e); } } }
// [JACKSON-484] public void testInetAddress() throws IOException { InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class); assertEquals("127.0.0.1", address.getHostAddress()); // should we try resolving host names? That requires connectivity... final String HOST = "google.com"; address = MAPPER.readValue(quote(HOST), InetAddress.class); assertEquals(HOST, address.getHostName()); }
/** Return the hostname of the local machine. */ public static String getLocalHost() { String hostname = null; try { InetAddress ia = InetAddress.getLocalHost(); hostname = ia.getHostName(); } catch (UnknownHostException e) { return "localhost"; } return hostname; }
protected String getHostName() { String res = ConfigManager.getPlatformHostname(); if (res == null) { try { InetAddress inet = InetAddress.getLocalHost(); return inet.getHostName(); } catch (UnknownHostException e) { log.warning("Can't get hostname", e); return "unknown"; } } return res; }
/** * Returns the name of the localhost. If that cannot be found it will return <code>localhost * </code>. * * @return my host */ public static String myHost() { String str = null; try { InetAddress inetA = InetAddress.getLocalHost(); str = inetA.getHostName(); } catch (UnknownHostException exc) { } if (str == null) { str = "localhost"; } return str; }
/** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("versió 0.1 del projecte prjava02"); try { InetAddress adreça = InetAddress.getLocalHost(); String hostname = adreça.getHostName(); System.out.println("hostname=" + hostname); System.out.println("Nom de l'usuari: " + System.getProperty("user.name")); System.out.println("Carpeta Personal: " + System.getProperty("user.home")); System.out.println("Sistema operatiu: " + System.getProperty("os.name")); System.out.println("Versió OS: " + System.getProperty("os.version")); System.out.println("Creació d'una branca del projecte prjava02 "); System.out.println("Afegint més codi a la branca00 del projecte prjava02"); } catch (IOException e) { } }
/* * Returns the string representation of the address that this * listen key represents. */ public String address() { InetAddress address = ss.getInetAddress(); /* * If bound to the wildcard address then use current local * hostname. In the event that we don't know our own hostname * then assume that host supports IPv4 and return something to * represent the loopback address. */ if (address.isAnyLocalAddress()) { try { address = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { byte[] loopback = {0x7f, 0x00, 0x00, 0x01}; try { address = InetAddress.getByAddress("127.0.0.1", loopback); } catch (UnknownHostException x) { throw new InternalError("unable to get local hostname"); } } } /* * Now decide if we return a hostname or IP address. Where possible * return a hostname but in the case that we are bound to an * address that isn't registered in the name service then we * return an address. */ String result; String hostname = address.getHostName(); String hostaddr = address.getHostAddress(); if (hostname.equals(hostaddr)) { if (address instanceof Inet6Address) { result = "[" + hostaddr + "]"; } else { result = hostaddr; } } else { result = hostname; } /* * Finally return "hostname:port", "ipv4-address:port" or * "[ipv6-address]:port". */ return result + ":" + ss.getLocalPort(); }
private static void aguardarConexao() throws Exception { ServidorApp.srvApp = new ServerSocket(_porta); System.out.println("\nA Porta " + _porta + " foi ABERTA! \nAguardando nova conexao..."); InetAddress inet = InetAddress.getByName("localhost"); while (true) { ServidorApp.sk = srvApp.accept(); System.out.println("Informacao coletada do cliente..."); System.out.println(inet.getHostAddress()); System.out.println(inet.getHostName()); BufferedReader recebercliente = new BufferedReader(new InputStreamReader(sk.getInputStream())); ServidorApp.msg_cliente = recebercliente.readLine(); System.out.println("Mensagem Recebida do Cliente: " + msg_cliente); } }
public LoginBox() { super("VnmrJ Login"); dolayout("", "", ""); setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); // setVast(); DisplayOptions.addChangeListener(this); try { InetAddress inetAddress = InetAddress.getLocalHost(); m_strHostname = inetAddress.getHostName(); } catch (Exception e) { m_strHostname = "localhost"; } VNMRFrame vnmrFrame = VNMRFrame.getVNMRFrame(); Dimension size = vnmrFrame.getSize(); position = vnmrFrame.getLocationOnScreen(); AppIF appIF = Util.getAppIF(); int h = appIF.statusBar.getSize().height; width = size.width; height = size.height - h; // Allow resizing and use the previous size and position // To stop resizing, use setResizable(false); readPersistence(); // setSize(width, height); // setLocation(position); // setResizable(false); setBackgroundColor(Util.getBgColor()); m_trayTimer = new javax.swing.Timer( 6000, new ActionListener() { public void actionPerformed(ActionEvent e) { setTrays(); } }); }
/** * This constructor is where the real work takes place. Connect to the specified address and port. * Use default local values if not specified, otherwise use the local host and port passed in. * Create as stream or datagram based on "stream" argument. * * <p> * * @param raddr The remote address to connect to * @param rport The remote port to connect to * @param laddr The local address to connect to * @param lport The local port to connect to * @param stream true for a stream socket, false for a datagram socket * @exception IOException If an error occurs * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport, boolean stream) throws IOException { this(); this.inputShutdown = false; this.outputShutdown = false; if (impl == null) throw new IOException("Cannot initialize Socket implementation"); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(raddr.getHostName(), rport); impl.create(stream); // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port, // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as // that default. JDK 1.2 doc infers not to do a bind. if (laddr != null) impl.bind(laddr, lport); if (raddr != null) impl.connect(raddr, rport); }
@Override public void run() { try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); textArea.append("TCP connection listener started at " + new Date() + '\n'); while (true) { // Listen for a new connection request Socket socket = serverSocket.accept(); // Display the client number textArea.append( "Starting thread for TCP client " + clientNo + " at " + new Date() + '\n'); // Find the client's host name, and IP address InetAddress inetAddress = socket.getInetAddress(); textArea.append( "Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n"); textArea.append( "Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n"); // Create a new thread for the TCP connection HandleTCPClient task = new HandleTCPClient(socket); // Start the new thread new Thread(task).start(); // Increment clientNo clientNo++; } } catch (IOException ex) { System.err.println(ex); } }
/** * Returns the local address to which this socket is bound. If this socket is not connected, then * <code>null</code> is returned. * * @return The local address * @since 1.1 */ public InetAddress getLocalAddress() { if (impl == null) return null; InetAddress addr = null; try { addr = (InetAddress) impl.getOption(SocketOptions.SO_BINDADDR); } catch (SocketException e) { // (hopefully) shouldn't happen // throw new java.lang.InternalError // ("Error in PlainSocketImpl.getOption"); return null; } // FIXME: According to libgcj, checkConnect() is supposed to be called // before performing this operation. Problems: 1) We don't have the // addr until after we do it, so we do a post check. 2). The docs I // see don't require this in the Socket case, only DatagramSocket, but // we'll assume they mean both. SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(addr.getHostName(), getLocalPort()); return addr; }
/** @param args the command line arguments */ public static void main(String[] args) { System.out.println("versió 0.1 del projecte prjava02"); try { InetAddress adreça = InetAddress.getLocalHost(); String hostname = adreça.getHostName(); System.out.println("hostname=" + hostname); System.out.println("Nom de l'usuari: " + System.getProperty("user.name")); System.out.println("Carpeta Personal: " + System.getProperty("user.home")); System.out.println("Sistema operatiu: " + System.getProperty("os.name")); System.out.println("Versió OS: " + System.getProperty("os.version")); } catch (IOException e) { } }
// initiate either a server or a user session public void run() { if (isDaemon) { daemon(); return; } ; boolean loggedIn = false; int i, h1; String di, str1, user = "******", user_id = "0"; InetAddress localNode; byte dataBuffer[] = new byte[1024]; String command = null; StringBuffer statusMessage = new StringBuffer(40); File targetFile = null; try { // start mysql Class.forName("com.mysql.jdbc.Driver").newInstance(); this.db_conn = DriverManager.getConnection(db_url); this.db_stmt = this.db_conn.createStatement(); this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')"); incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout remoteNode = incoming.getInetAddress(); localNode = InetAddress.getLocalHost(); BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET)); PrintWriter out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true); str1 = "220 Flickr FTP Server Ready"; out.println(str1); if (log) System.out.println(remoteNode.getHostName() + " " + str1); boolean done = false; char dataType = 0; while (!done) { statusMessage.setLength(0); // obtain and tokenize command String str = in.readLine(); if (str == null) break; // EOS reached i = str.indexOf(' '); if (i == -1) i = str.length(); command = str.substring(0, i).toUpperCase().intern(); if (log) System.out.print( user + "@" + remoteNode.getHostName() + " " + (String) ((command != "PASS") ? str : "PASS ***")); str = str.substring(i).trim(); try { if (command == "USER") { user = str; statusMessage.append("331 Password"); } else if (command == "PASS") { String pass = str; String pass_md5 = md5(pass); this.db_rs = this.db_stmt.executeQuery( "SELECT * FROM users WHERE email='" + user + "' AND password='******'"); if (this.db_rs.first()) { loggedIn = true; user_id = this.db_rs.getString("id"); System.out.println("Account id is " + user_id); } statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect"); } else if (!loggedIn) { statusMessage.append("530 Not logged in"); } else if (command == "RETR") { statusMessage.append("999 Not likely"); } else if (command == "STOR") { out.println(BINARY_XFER); // trim a leading slash off the filename if there is one if (str.substring(0, 1).equals("/")) str = str.substring(1); String filename = user_id + "_" + str; // TODO: sanitise filename targetFile = new File(upload_root + "/" + filename); RandomAccessFile dataFile = null; InputStream inStream = null; OutputStream outStream = null; BufferedReader br = null; PrintWriter pw = null; try { int amount; dataSocket = setupDataLink(); // ensure timeout on reads. dataSocket.setSoTimeout(inactivityTimer); dataFile = new RandomAccessFile(targetFile, "rw"); inStream = dataSocket.getInputStream(); while ((amount = inStream.read(dataBuffer)) != -1) dataFile.write(dataBuffer, 0, amount); statusMessage.append(XFER_COMPLETE); shell_exec(ingest_path + " " + user_id + " " + filename); } finally { try { if (inStream != null) inStream.close(); } catch (Exception e1) { } ; try { if (outStream != null) outStream.close(); } catch (Exception e1) { } ; try { if (dataFile != null) dataFile.close(); } catch (Exception e1) { } ; try { if (dataSocket != null) dataSocket.close(); } catch (Exception e1) { } ; dataSocket = null; } } else if (command == "REST") { statusMessage.append("502 Sorry, no resuming"); } else if (command == "TYPE") { if (Character.toUpperCase(str.charAt(0)) == 'I') { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504 Only binary baybee"); } } else if (command == "DELE" || command == "RMD" || command == "XRMD" || command == "MKD" || command == "XMKD" || command == "RNFR" || command == "RNTO" || command == "CDUP" || command == "XCDUP" || command == "CWD" || command == "SIZE" || command == "MDTM") { statusMessage.append("502 None of that malarky!"); } else if (command == "QUIT") { statusMessage.append(COMMAND_OK).append("GOOD BYE"); done = true; } else if (command == "PWD" | command == "XPWD") { statusMessage.append("257 \"/\" is current directory"); } else if (command == "PORT") { int lng, lng1, lng2, ip2; String a1 = "", a2 = ""; lng = str.length() - 1; lng2 = str.lastIndexOf(","); lng1 = str.lastIndexOf(",", lng2 - 1); for (i = lng1 + 1; i < lng2; i++) { a1 = a1 + str.charAt(i); } for (i = lng2 + 1; i <= lng; i++) { a2 = a2 + str.charAt(i); } remotePort = Integer.parseInt(a1); ip2 = Integer.parseInt(a2); remotePort = (remotePort << 8) + ip2; statusMessage.append(COMMAND_OK).append(remotePort); } else if (command == "LIST" | command == "NLST") { try { out.println("150 ASCII data"); dataSocket = setupDataLink(); PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true); if ((command == "NLST")) { out2.println("."); out2.println(".."); } else { out2.println("total 8.0k"); out2.println("dr--r--r-- 1 owner group 213 Aug 26 16:31 ."); out2.println("dr--r--r-- 1 owner group 213 Aug 26 16:31 .."); } // socket MUST be closed before signalling EOD dataSocket.close(); dataSocket = null; statusMessage.setLength(0); statusMessage.append(XFER_COMPLETE); } finally { try { if (dataSocket != null) dataSocket.close(); } catch (Exception e) { } ; dataSocket = null; } } else if (command == "NOOP") { statusMessage.append(COMMAND_OK); } else if (command == "SYST") { statusMessage.append("215 UNIX"); // allows NS to do long dir } else if (command == "MODE") { if (Character.toUpperCase(str.charAt(0)) == 'S') { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504"); } } else if (command == "STRU") { if (str.equals("F")) { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504"); } } else if (command == "PASV") { try { int num = 0, j = 0; if (passiveSocket != null) try { passiveSocket.close(); } catch (Exception e) { } ; passiveSocket = new ServerSocket(0); // any port // ensure timeout on reads. passiveSocket.setSoTimeout(inactivityTimer); statusMessage.append("227 Entering Passive Mode ("); String s = localNode.getHostAddress().replace('.', ','); // get host # statusMessage.append(s).append(','); num = passiveSocket.getLocalPort(); // get port # j = (num >> 8) & 0xff; statusMessage.append(j); statusMessage.append(','); j = num & 0xff; statusMessage.append(j); statusMessage.append(')'); } catch (Exception e) { try { if (passiveSocket != null) passiveSocket.close(); } catch (Exception e1) { } ; passiveSocket = null; throw e; } } else { statusMessage.append("502 unimplemented ").append(command); } } // shutdown causes an interruption to be thrown catch (InterruptedException e) { throw (e); } catch (Exception e) // catch all for any errors (including files) { statusMessage.append(FAULT).append(e.getMessage()); if (debug) { System.out.println("\nFAULT - lastfile " + targetFile); e.printStackTrace(); } ; } // send result status to remote out.println(statusMessage); if (log) System.out.println("\t" + statusMessage); } } catch (Exception e) // usually network errors (including timeout) { if (log) System.out.println("forced instance exit " + e); if (debug) e.printStackTrace(); } finally // exiting server instance { // tear down mysql if (this.db_rs != null) { try { this.db_rs.close(); } catch (SQLException SQLE) {; } } if (this.db_stmt != null) { try { this.db_stmt.close(); } catch (SQLException SQLE) {; } } if (this.db_pstmt != null) { try { this.db_pstmt.close(); } catch (SQLException SQLE) {; } } if (this.db_conn != null) { try { this.db_conn.close(); } catch (SQLException SQLE) {; } } forceClose(); } }
public static void main(String[] args) throws IOException, InterruptedException { System.out.println("Auction Server starting"); try { // Get hostname by textual representation of IP address InetAddress addr = InetAddress.getLocalHost(); // = InetAddress.getByName("127.0.0.1"); String hostname = addr.getHostName(); // Get the host name System.out.println("ip address = " + addr.toString() + "\nHost name = " + hostname); } catch (UnknownHostException e) { } // used to let host user control flow of program BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // System.out.println("How many players are needed?"); int numPlayersNeeded = 2; // Integer.valueOf(br.readLine()); // make an auction with which clients interact Auction myAuction = new Auction(5, numPlayersNeeded); // auction with 5 slots // SELECT TYPE OF AUCTION Vector<SimultaneousAscendingAuctionServerThread> myThreads = new Vector<SimultaneousAscendingAuctionServerThread>(); ServerSocket serverSocket = null; int portNum = 7; // the luckiest port there is! // Try reading in the IP and socket number from the text file... try { BufferedReader in = new BufferedReader(new FileReader("./src/IP_and_Port.txt")); // two lines in this file. First is hostName/IP address, and second is socket number of host String hName = in.readLine(); // use the hostname found above and skip this one portNum = Integer.valueOf(in.readLine()); in.close(); } catch (IOException e) { } try { serverSocket = new ServerSocket(portNum); } catch (IOException e) { System.err.println("AuctionServer could not listen on port: " + portNum + "."); System.exit(-1); } System.out.println("Clients should join the auction now..."); boolean started = false; boolean firstThread = true; // used to designate first thread as "reporter" while (!started) { // (listening && !myAuction.isOver() ){ SimultaneousAscendingAuctionServerThread aThread = new SimultaneousAscendingAuctionServerThread( serverSocket.accept(), myAuction, numPlayersNeeded); // set first thread as the "reporter", so only one copy of info printed to cmd prompt aThread.start(); if (firstThread) { aThread.setReporter(true); firstThread = false; } myThreads.add(aThread); if (myThreads.size() >= numPlayersNeeded) { started = true; System.out.println("Auction should be ready to go..."); } else System.out.println( "need more players. Thread-count = " + myThreads.size() + " , idCount = " + myAuction.bidderIDs.size()); // myAuction was passed as a shallow copy... so only one auction exists } System.out.println("\nAuction has started with " + myThreads.size() + " agents!\n"); // The auction is running right now... can you feel it? // System.out.println("Press Enter to end host connections and close..."); // br.readLine(); // System.out.println("Auction is complete... closing connections"); for (int i = 0; i < myThreads.size(); i++) myThreads.get(i).join(); for (int i = 0; i < myThreads.size(); i++) if (myThreads.get(i).isAlive()) myThreads.get(i).closeConnection(); serverSocket.close(); } // end main()