List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:org.jivesoftware.smack.XMPPConnection.java
/** * The server has indicated that TLS negotiation can start. We now need to secure the * existing plain connection and perform a handshake. This method won't return until the * connection has finished the handshake or an error occured while securing the connection. * * @throws Exception if an exception occurs. *///from w w w. j ava 2 s. c om void proceedTLSReceived() throws Exception { SSLContext context = SSLContext.getInstance("TLS"); KeyStore ks = null; KeyManager[] kms = null; PasswordCallback pcb = null; if (config.getCallbackHandler() == null) { ks = null; } else { //System.out.println("Keystore type: "+configuration.getKeystoreType()); if (config.getKeystoreType().equals("NONE")) { ks = null; pcb = null; } else if (config.getKeystoreType().equals("PKCS11")) { try { Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11") .getConstructor(InputStream.class); String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library(); ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes()); Provider p = (Provider) c.newInstance(config); Security.addProvider(p); ks = KeyStore.getInstance("PKCS11", p); pcb = new PasswordCallback("PKCS11 Password: ", false); this.config.getCallbackHandler().handle(new Callback[] { pcb }); ks.load(null, pcb.getPassword()); } catch (Exception e) { ks = null; pcb = null; } } else if (config.getKeystoreType().equals("Apple")) { ks = KeyStore.getInstance("KeychainStore", "Apple"); ks.load(null, null); //pcb = new PasswordCallback("Apple Keychain",false); //pcb.setPassword(null); } else { ks = KeyStore.getInstance(config.getKeystoreType()); try { pcb = new PasswordCallback("Keystore Password: ", false); config.getCallbackHandler().handle(new Callback[] { pcb }); ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword()); } catch (Exception e) { ks = null; pcb = null; } } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); try { if (pcb == null) { kmf.init(ks, null); } else { kmf.init(ks, pcb.getPassword()); pcb.clearPassword(); } kms = kmf.getKeyManagers(); } catch (NullPointerException npe) { kms = null; } } // Verify certificate presented by the server context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) }, new java.security.SecureRandom()); Socket plain = socket; // Secure the plain connection socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(), plain.getPort(), true); socket.setSoTimeout(0); socket.setKeepAlive(true); // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Proceed to do the handshake ((SSLSocket) socket).startHandshake(); //if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println("Connection wants client auth"); //} //else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println("Connection needs client auth"); //} //else { // System.err.println("Connection does not require client auth"); // } // Set that TLS was successful usingTLS = true; // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); }
From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java
public TunneledSSLConnection(Socket socket, String destinationHostname) throws SSLException, IOException, GeneralSecurityException { LOGGER.trace("Instantiating TunneledSSLConnection"); this.destinationHostname = destinationHostname; this.socket = socket; if (socket == null) { IllegalArgumentException e = new IllegalArgumentException("socket cannot be null"); LOGGER.error("Socket cannot be null", e); throw e;/*from w ww .j a va 2 s.c o m*/ } if (destinationHostname == null) { IllegalArgumentException e = new IllegalArgumentException("destinationHostname cannot be null"); LOGGER.error("destinationHostname cannot be null", e); throw e; } SSLSocketFactory sslSocketFactory = initializeSSLFactory(); HttpParams params = MiscHttpFactory.createDefaultHttpProxyParams(); int buffersize = HttpConnectionParams.getSocketBufferSize(params); sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(false); sslInputStream = sslSocket.getInputStream(); sslTunnelInputBuffer = new SSLTunnelInputBuffer(sslInputStream, buffersize, params); sslOutputStream = sslSocket.getOutputStream(); sslTunnelOutputBuffer = new SSLTunnelOutputBuffer(sslOutputStream, buffersize, params); // This is the real important part where we identify the buffers to the parent init(sslTunnelInputBuffer, sslTunnelOutputBuffer, params); open = true; }
From source file:runtime.starter.MPJRun.java
/** * Every thing is being inside this constructor :-) *///from w w w .ja v a 2 s . co m public MPJRun(String args[]) throws Exception { java.util.logging.Logger logger1 = java.util.logging.Logger.getLogger(""); // remove all existing log handlers: remove the ERR handler for (java.util.logging.Handler h : logger1.getHandlers()) { logger1.removeHandler(h); } Map<String, String> map = System.getenv(); try { mpjHomeDir = map.get("MPJ_HOME"); RTConstants.MPJ_HOME_DIR = mpjHomeDir; if (mpjHomeDir == null) { throw new Exception("MPJ_HOME environment variable not set!!!"); } } catch (Exception exc) { System.out.println("Error: " + exc.getMessage()); exc.printStackTrace(); return; } readValuesFromMPJExpressConf(); createLogger(args); if (DEBUG && logger.isDebugEnabled()) { logger.info(" --MPJRun invoked--"); logger.info(" adding shutdown hook thread"); } if (DEBUG && logger.isDebugEnabled()) { logger.info("processInput called ..."); } processInput(args); /* the code is running in the multicore configuration */ if (deviceName.equals("multicore")) { System.out.println("MPJ Express (" + VERSION + ") is started in the " + "multicore configuration"); if (DEBUG && logger.isDebugEnabled()) { logger.info("className " + className); } int jarOrClass = (applicationClassPathEntry.endsWith(".jar") ? RUNNING_JAR_FILE : RUNNING_CLASS_FILE); MulticoreDaemon multicoreDaemon = new MulticoreDaemon(className, applicationClassPathEntry, jarOrClass, nprocs, wdir, jvmArgs, appArgs, mpjHomeDir, ADEBUG, APROFILE, DEBUG_PORT); return; } else { /* cluster configuration */ System.out.println("MPJ Express (" + VERSION + ") is started in the " + "cluster configuration with " + deviceName); } machineList = MPJUtil.readMachineFile(machinesFile); for (int i = machineList.size(); i > nprocs; i--) { machineList.remove(i - 1); } machinesSanityCheck(); // Changed to incorporate hybrid device configuration if (deviceName.equals("hybdev")) assignTasksHyb(); else assignTasks(); if (ADEBUG) { writeFile(CONF_FILE_CONTENTS + "\n"); } urlArray = applicationClassPathEntry.getBytes(); peerSockets = new Vector<Socket>(); clientSocketInit(); int peersStartingRank = 0; for (int j = 0; j < peerSockets.size(); j++) { Socket peerSock = peerSockets.get(j); if (DEBUG && logger.isDebugEnabled()) { logger.debug("procsPerMachineTable " + procsPerMachineTable); } /* * FIXME: should we not be checking all IP addresses of remote machine? * Does it make sense? */ String hAddress = peerSock.getInetAddress().getHostAddress(); String hName = peerSock.getInetAddress().getHostName(); Integer nProcessesInt = ((Integer) procsPerMachineTable.get(hName)); if (nProcessesInt == null) { nProcessesInt = ((Integer) procsPerMachineTable.get(hAddress)); } int nProcesses = nProcessesInt.intValue(); if (deviceName.equals("hybdev")) { pack(nProcesses, j, peerSock); // starting NETID of hybrid // device should be adjusted // according to node // (NioProcessCount, // StartingRank) } else { pack(nProcesses, peersStartingRank, peerSock); peersStartingRank += nProcesses; } if (DEBUG && logger.isDebugEnabled()) { logger.debug("Sending to " + peerSock); } } if (DEBUG && logger.isDebugEnabled()) { logger.debug("procsPerMachineTable " + procsPerMachineTable); } }
From source file:org.eredlab.g4.ccl.net.bsd.RCommandClient.java
InputStream _createErrorStream() throws IOException { int localPort; ServerSocket server;/*from ww w . j av a 2s .c om*/ Socket socket; localPort = MAX_CLIENT_PORT; server = null; // Keep compiler from barfing for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort) { try { server = _socketFactory_.createServerSocket(localPort, 1, getLocalAddress()); } catch (SocketException e) { continue; } break; } if (localPort < MIN_CLIENT_PORT) throw new BindException("All ports in use."); _output_.write(Integer.toString(server.getLocalPort()).getBytes()); _output_.write('\0'); _output_.flush(); socket = server.accept(); server.close(); if (isRemoteVerificationEnabled() && !verifyRemote(socket)) { socket.close(); throw new IOException("Security violation: unexpected connection attempt by " + socket.getInetAddress().getHostAddress()); } return (new SocketInputStream(socket, socket.getInputStream())); }
From source file:com.isecpartners.gizmo.HttpRequest.java
private SSLSocket negotiateSSL(Socket sock, String hostname) throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, IOException, InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException { synchronized (_factories) { SSLSocketFactory factory = _factories.get(hostname); if (factory == null) { factory = initSSL(hostname); }//from w w w . ja va 2 s .co m String inbound_hostname = sock.getInetAddress().getHostName(); int inbound_port = sock.getPort(); SSLSocket sslsock = (SSLSocket) factory.createSocket(sock, inbound_hostname, inbound_port, true); sslsock.setUseClientMode(false); if (!sslsock.isConnected()) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, "Couldn't negotiate SSL"); System.exit(-1); } return sslsock; } }
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
public boolean isSameAddress(MsgContext ep) { Socket s = (Socket) ep.getNote(socketNote); return isSameAddress(s.getLocalAddress(), s.getInetAddress()); }
From source file:com.stratuscom.harvester.codebase.ClassServer.java
private boolean processRequest(Socket sock) { try {// w w w .j a v a2 s. c om DataOutputStream out = new DataOutputStream(sock.getOutputStream()); String req; try { req = getInput(sock, true); } catch (Exception e) { logger.log(Level.FINE, "reading request", e); return true; } if (req == null) { return true; } String[] args = new String[3]; boolean get = req.startsWith("GET "); if (!get && !req.startsWith("HEAD ")) { processBadRequest(args, out); } String path = parsePathFromRequest(req, get); if (path == null) { return processBadRequest(args, out); } if (args != null) { args[0] = path; } args[1] = sock.getInetAddress().getHostName(); args[2] = Integer.toString(sock.getPort()); logger.log(Level.FINER, get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE, args); byte[] bytes; try { bytes = getBytes(path); } catch (Exception e) { logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e); out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n"); out.flush(); return true; } if (bytes == null) { logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path); out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n"); out.flush(); return true; } writeHeader(out, bytes); if (get) { out.write(bytes); } out.flush(); return false; } catch (Exception e) { logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e); } finally { try { sock.close(); } catch (IOException e) { } } return false; }
From source file:pubsub.io.android.PubsubComm.java
/** * Start the ConnectedThread to begin managing a Bluetooth connection * // ww w. ja va2s . c o m * @param socket * The BluetoothSocket on which the connection was made * @param device * The BluetoothDevice that has been connected */ public synchronized void connected(Socket socket, String sub) { Log.d(TAG, "connected"); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(Pubsub.CONNECTED_TO_HOST); Bundle bundle = new Bundle(); bundle.putString(Pubsub.HOST_NAME, socket.getInetAddress().getHostName()); msg.setData(bundle); mHandler.sendMessage(msg); // Notify the activity that subscribes are now safe! mHandler.obtainMessage(Pubsub.SUBSCRIBES).sendToTarget(); setState(STATE_CONNECTED); // Subscribe to the defined sub try { write(PubsubParser.sub(sub).getBytes()); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.jcraft.weirdx.WeirdX.java
public void weirdx_start(Container container) throws ConnectException { if (xdmcpmode != null) { LOG.debug("XDMC Mode = " + xdmcpmode); if (xdmcpmode.equals("query")) { xdmcp = new XDMCP(xdmcpaddr, myAddress, displayNumber); } else if (xdmcpmode.equals("broadcast")) { xdmcp = new XDMCP(XDMCP.BroadcastQuery, xdmcpaddr, myAddress, displayNumber); } else if (xdmcpmode.equals("indirect")) { xdmcp = new XDMCP(XDMCP.IndirectQuery, xdmcpaddr, myAddress, displayNumber); }/*from w w w .ja v a2 s . c o m*/ } if (sxrexec != null && sxrexec.equals("yes")) { xrexec = new XRexec(myAddress, displayNumber); } weirdx_init(container); InputStream in; OutputStream out; InputOutput client = null; if (xdmcp != null) { Client.addListener((ClientListener) xdmcp); xdmcp.start(); } if (jdxpc != null) { (new SpawnJDxpc(this)).start(); } if (ssshrexec != null) { if (ssshrexec.equals("yes")) { (new SpawnSSHRexec(this)).start(); } } byte[] byte_order = new byte[1]; try { Socket socket = null; while (true && weirdx != null) { try { socket = displaysocket.accept(); } catch (Exception e) { LOG.error(e); if (e instanceof NullPointerException) { weirdx = null; break; } continue; } if (!Acl.check(socket.getInetAddress())) { LOG.error("ACL warning: unauthorized access from " + socket.getInetAddress()); try { socket.close(); } catch (Exception e) { } ; continue; } try { socket.setTcpNoDelay(true); } catch (Exception eeee) { //System.out.println(eeee+" tcpnodelay"); } client = null; in = socket.getInputStream(); out = socket.getOutputStream(); try { in.read(byte_order, 0, 1); } catch (Exception e) { continue; } // 0x6c LSB // 0x42 MSB if (byte_order[0] == 0x6c) { client = new IOLSB(); } else if (byte_order[0] == 0x42) { client = new IOMSB(); } else { LOG.warn("protocol: error " + Integer.toHexString(byte_order[0])); continue; } client.setInputStream(in); client.setOutputStream(out); Client foo = new Client(client); if (foo.index != -1) { foo.start(); } else { // System.err.println("running over clients table"); } } } catch (IOException e) { LOG.error("IO Error: " + e.getLocalizedMessage()); } // stop(); // ?? }
From source file:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();//from www . j ava 2 s. c om CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }