List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:com.nokia.dempsy.messagetransport.tcp.TcpReceiver.java
private static String getClientDescription(Socket socket) { try {/*w w w.j av a 2s .co m*/ return "(" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + ")"; } catch (Throwable th) { return "(Unknown Client)"; } }
From source file:org.openadaptor.auxil.connector.socket.SocketReadConnector.java
private static String getConnectionName(Socket s) { return s.getInetAddress().getHostAddress() + ":" + s.getPort(); }
From source file:SocketFetcher.java
/** * Start TLS on an existing socket. Supports the "STARTTLS" command in many * protocols./*from w ww .j a va2 s . c o m*/ */ public static Socket startTLS(Socket socket, Properties props, String prefix) throws IOException { InetAddress a = socket.getInetAddress(); String host = a.getHostName(); int port = socket.getPort(); // System.out.println("SocketFetcher: startTLS host " + host + ", port " + // port); try { SSLSocketFactory ssf; String sfClass = props.getProperty(prefix + ".socketFactory.class", null); SocketFactory sf = getSocketFactory(sfClass); if (sf != null && sf instanceof SSLSocketFactory) ssf = (SSLSocketFactory) sf; else ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = ssf.createSocket(socket, host, port, true); configureSSLSocket(socket, props, prefix); } catch (Exception ex) { if (ex instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) ex).getTargetException(); if (t instanceof Exception) ex = (Exception) t; } if (ex instanceof IOException) throw (IOException) ex; // wrap anything else before sending it on IOException ioex = new IOException( "Exception in startTLS: host " + host + ", port " + port + "; Exception: " + ex); throw ioex; } return socket; }
From source file:SocketFetcher.java
/** * Start TLS on an existing socket.// w w w .j a va2s.co m * Supports the "STARTTLS" command in many protocols. */ public static Socket startTLS(Socket socket, Properties props, String prefix) throws IOException { InetAddress a = socket.getInetAddress(); String host = a.getHostName(); int port = socket.getPort(); //System.out.println("SocketFetcher: startTLS host " + host + ", port " + port); try { SSLSocketFactory ssf; String sfClass = props.getProperty(prefix + ".socketFactory.class", null); SocketFactory sf = getSocketFactory(sfClass); if (sf != null && sf instanceof SSLSocketFactory) ssf = (SSLSocketFactory) sf; else ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = ssf.createSocket(socket, host, port, true); configureSSLSocket(socket, props, prefix); } catch (Exception ex) { if (ex instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) ex).getTargetException(); if (t instanceof Exception) ex = (Exception) t; } if (ex instanceof IOException) throw (IOException) ex; // wrap anything else before sending it on IOException ioex = new IOException( "Exception in startTLS: host " + host + ", port " + port + "; Exception: " + ex); ioex.initCause(ex); throw ioex; } return socket; }
From source file:expect4j.ExpectUtils.java
/** * Creates an HTTP client connection to a specified HTTP server and * returns the entire response. This function simulates <code>curl * http://remotehost/url</code>.//www.j a v a2s .co m * * @param remotehost the DNS or IP address of the HTTP server * @param url the path/file of the resource to look up on the HTTP * server * @return the response from the HTTP server * @throws Exception upon a variety of error conditions */ public static String Http(String remotehost, String url) throws Exception { Socket s = null; s = new Socket(remotehost, 80); logger.debug("Connected to " + s.getInetAddress().toString()); if (false) { // for serious connection-oriented debugging only PrintWriter out = new PrintWriter(s.getOutputStream(), false); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); System.out.println("Sending request"); out.print("GET " + url + " HTTP/1.1\r\n"); out.print("Host: " + remotehost + "\r\n"); out.print("Connection: close\r\n"); out.print("User-Agent: Expect4j\r\n"); out.print("\r\n"); out.flush(); System.out.println("Request sent"); System.out.println("Receiving response"); String line; while ((line = in.readLine()) != null) System.out.println(line); System.out.println("Received response"); if (line == null) System.exit(0); } Expect4j expect = new Expect4j(s); logger.debug("Sending HTTP request for " + url); expect.send("GET " + url + " HTTP/1.1\r\n"); expect.send("Host: " + remotehost + "\r\n"); expect.send("Connection: close\r\n"); expect.send("User-Agent: Expect4j\r\n"); expect.send("\r\n"); logger.debug("Waiting for HTTP response"); String remaining = null; expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() { public void run(ExpectState state) { logger.trace("Detected HTTP Response Header"); // save http code String match = state.getMatch(); String parts[] = match.split(" "); state.addVar("httpCode", parts[1]); state.exp_continue(); } }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() { public void run(ExpectState state) { logger.trace("Detected Content-Type header"); state.addVar("contentType", state.getMatch()); state.exp_continue(); } }), new EofMatch(new Closure() { // should cause entire page to be collected public void run(ExpectState state) { logger.trace("Found EOF, done receiving HTTP response"); } }), // Will cause buffer to be filled up till end new TimeoutMatch(10000, new Closure() { public void run(ExpectState state) { logger.trace("Timeout waiting for HTTP response"); } }) }); remaining = expect.getLastState().getBuffer(); // from EOF matching String httpCode = (String) expect.getLastState().getVar("httpCode"); String contentType = (String) expect.getLastState().getVar("contentType"); s.close(); return remaining; }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Setup SSL connection./* w w w . j a v a 2 s . c o m*/ */ private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException { if (DEBUG) { Log.d(TAG, "Load custom SSL certificates"); } final SSLContext sslContext; try { // Load SSL certificates: // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html // Earlier Android versions do not have updated root CA // certificates, resulting in connection errors. final KeyStore keyStore = loadCertificates(context); final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore); final TrustManager[] tms = new TrustManager[] { customTrustManager }; // Init SSL connection with custom certificates. // The same SecureRandom instance is used for every connection to // speed up initialization. sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, SECURE_RANDOM); } catch (GeneralSecurityException e) { final IOException ioe = new IOException("Failed to initialize SSL engine"); ioe.initCause(e); throw ioe; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Fix slow read: // http://code.google.com/p/android/issues/detail?id=13117 // Prior to ICS, the host name is still resolved even if we already // know its IP address, for each connection. final SSLSocketFactory delegate = sslContext.getSocketFactory(); final SSLSocketFactory socketFactory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; conn.setSSLSocketFactory(socketFactory); } else { conn.setSSLSocketFactory(sslContext.getSocketFactory()); } conn.setHostnameVerifier(new BrowserCompatHostnameVerifier()); }
From source file:Main.java
/** * Renders the details of a socket in the returned string * @param socket The socket to render//from ww w.j av a2 s.co m * @return the details of the socket as a string */ public static String render(Socket socket) { if (socket == null) return "NULL"; StringBuilder b = new StringBuilder("\nSocket ["); b.append("\n\tLocalPort:").append(socket.getLocalPort()); b.append("\n\tLocalAddress:").append(socket.getLocalAddress()); b.append("\n\tLocalSocketAddress:").append(socket.getLocalSocketAddress()); b.append("\n\tRemotePort:").append(socket.getPort()); b.append("\n\tRemoteAddress:").append(socket.getInetAddress()); b.append("\n\tRemoteSocketAddress:").append(socket.getRemoteSocketAddress()); b.append("\n\tChannel:").append(socket.getChannel()); b.append("\n\tHashCode:").append(socket.hashCode()); b.append("\n]"); return b.toString(); }
From source file:de.fun2code.google.cloudprint.push.PushReceiver.java
/** * Sets up the SSL socket for use with XMPP. * /*from w ww . j a va 2s.c om*/ * @param socket * the socket to do TLS over. * @return The SSL Socket. * @throws IOException */ public static SSLSocket setupSSLSocket(Socket socket) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, IOException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); TrustManagerFactory tfactory = TrustManagerFactory.getInstance("SunPKIX"); tfactory.init(keyStore); SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslsocket.setUseClientMode(true); return sslsocket; }
From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java
/** * Setup SSL connection./*w w w . j ava 2s . c o m*/ */ private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException { final SSLContext sslContext; try { // SSL certificates are provided by the Guardian Project: // https://github.com/guardianproject/cacert if (trustManagers == null) { // Load SSL certificates: // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html // Earlier Android versions do not have updated root CA // certificates, resulting in connection errors. final KeyStore keyStore = loadCertificates(context); final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore); trustManagers = new TrustManager[] { customTrustManager }; } // Init SSL connection with custom certificates. // The same SecureRandom instance is used for every connection to // speed up initialization. sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, SECURE_RANDOM); } catch (GeneralSecurityException e) { final IOException ioe = new IOException("Failed to initialize SSL engine"); ioe.initCause(e); throw ioe; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Fix slow read: // http://code.google.com/p/android/issues/detail?id=13117 // Prior to ICS, the host name is still resolved even if we already // know its IP address, for each connection. final SSLSocketFactory delegate = sslContext.getSocketFactory(); final SSLSocketFactory socketFactory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; conn.setSSLSocketFactory(socketFactory); } else { conn.setSSLSocketFactory(sslContext.getSocketFactory()); } conn.setHostnameVerifier(new BrowserCompatHostnameVerifier()); }
From source file:com.iitb.cse.ConnectionInfo.java
static void handleConnection(Socket sock, Session session, int tid) { System.out.println("\n\n\n---------------->>>>>>>>>[" + tid + "]"); try {/* www . j ava 2s . c om*/ int count = 0; boolean newConnection = true; String ip_add = sock.getInetAddress().toString(); String[] _ip_add = ip_add.split("/"); String macAddress = ""; DeviceInfo myDevice = null; InputStream in = sock.getInputStream(); OutputStream out = sock.getOutputStream(); DataInputStream dis = new DataInputStream(in); DataOutputStream dos = new DataOutputStream(out); while (true) { System.out.println("\n[" + tid + "] My Socket : " + sock); String receivedData = ClientConnection.readFromStream(sock, dis, dos).trim(); if (receivedData.equals("") || receivedData == null) { System.out.println("\n[Empty/Null Data][" + tid + "]"); } else { System.out.println("\nReceived : " + receivedData); Map<String, String> jsonMap = null; JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @SuppressWarnings("rawtypes") @Override public List creatArrayContainer() { return new LinkedList(); } @SuppressWarnings("rawtypes") @Override public Map createObjectContainer() { return new LinkedHashMap(); } }; try { jsonMap = (Map<String, String>) parser.parse(receivedData, containerFactory); if (jsonMap != null) { String action = jsonMap.get(Constants.action); if (action.compareTo(Constants.heartBeat) == 0 || action.compareTo(Constants.heartBeat1) == 0 || action.compareTo(Constants.heartBeat2) == 0) { macAddress = jsonMap.get(Constants.macAddress); // heartbeat System.out.println("\n [" + tid + "] HeartBeat Received : " + (++count)); DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress)); if (device == null) { // first time from this device. ie new connection System.out.println("<<<== 1 ==>>>"); DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); newDevice.setBssid(jsonMap.get(Constants.bssid)); newDevice.setSsid(jsonMap.get(Constants.ssid)); // newDevice.setSsid(jsonMap.get(Constants.bssidList)); /* String apInfo = jsonMap.get(Constants.bssidList); if (apInfo != null || !apInfo.equals("")) { System.out.println("\nInside Bssid List1"); String[] bssidInfo = apInfo.split(";"); NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length]; for (int i = 0; i < bssidInfo.length; i++) { String[] info = bssidInfo[i].split(","); obj[i].setBssid(info[0]); obj[i].setRssi(info[1]); obj[i].setRssi(info[2]); } newDevice.setBssidList(obj); }*/ Date date = Utils.getCurrentTimeStamp(); newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setConnectionStatus(true); newDevice.setThread(Thread.currentThread()); newDevice.setSocket(sock); newDevice.setGetlogrequestsend(false); /* remaining parameters needs to be added!!! */ session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); } else // subsequent heartbeats / reconnection from same client if (newConnection) { // reconnection from same client System.out.println("<<<== 2 ==>>>"); if (device.thread != null) { device.thread.interrupt(); System.out.println("\n@#1[" + tid + "] Interrupting old thread"); } DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); newDevice.setBssid(jsonMap.get(Constants.bssid)); newDevice.setSsid(jsonMap.get(Constants.ssid)); /* String apInfo = jsonMap.get(Constants.bssidList); if (apInfo != null || !apInfo.equals("")) { System.out.println("\nInside Bssid List"); String[] bssidInfo = apInfo.split(";"); NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length]; for (int i = 0; i < bssidInfo.length; i++) { String[] info = bssidInfo[i].split(","); obj[i].setBssid(info[0]); obj[i].setRssi(info[1]); obj[i].setRssi(info[2]); } newDevice.setBssidList(obj); }*/ Date date = Utils.getCurrentTimeStamp(); newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setConnectionStatus(true); newDevice.setGetlogrequestsend(false); /* remaining parameters needs to be added!!! */ session.connectedClients.remove(device.macAddress); session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); if (session.filteredClients.contains(device)) { session.filteredClients.remove(device); session.filteredClients.add(newDevice); } } else { // heartbeat System.out.println("<<<== 3 ==>>>"); Date date = Utils.getCurrentTimeStamp(); device.setLastHeartBeatTime(date); device.setSocket(sock); device.setConnectionStatus(true); } } else if (action.compareTo(Constants.experimentOver) == 0) { macAddress = jsonMap.get(Constants.macAddress); System.out.println("\n[" + tid + "] Experiment Over Mesage received"); // experiment over // i need mac address from here // ip and port also preferred DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress)); if (device == null) { // new connection System.out.println("<<<== 4 ==>>>"); DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); //Date date = Utils.getCurrentTimeStamp(); //newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setGetlogrequestsend(false); newDevice.setConnectionStatus(true); newDevice.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), newDevice.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } /* remaining parameters needs to be added!!! */ session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); } else if (newConnection) { // reconnction from the same client System.out.println("<<<== 5 ==>>>"); if (device.thread != null) { device.thread.interrupt(); System.out.println("\n@#2[" + tid + "] Interrupting old thread"); } DeviceInfo newDevice = new DeviceInfo(); newDevice.setIp(jsonMap.get(Constants.ip)); newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port))); newDevice.setMacAddress(jsonMap.get(Constants.macAddress)); //Date date = Utils.getCurrentTimeStamp(); //newDevice.setLastHeartBeatTime(date); newDevice.setInpStream(dis); newDevice.setOutStream(dos); newDevice.setSocket(sock); newDevice.setThread(Thread.currentThread()); newDevice.setGetlogrequestsend(false); newDevice.setConnectionStatus(true); /* remaining parameters needs to be added!!! */ newDevice.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), newDevice.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } session.connectedClients.remove(device.macAddress); session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice); if (session.filteredClients.contains(device)) { session.filteredClients.remove(device); session.filteredClients.add(newDevice); } } else { System.out.println("<<<== 6 ==>>>"); // alread connected client // device.setExpOver(jsonMap.get(Constants.macAddress)) device.setConnectionStatus(true); device.setSocket(sock); device.setExpOver(1); // if (DBManager.updateExperimentOverStatus( Integer.parseInt(jsonMap.get(Constants.experimentNumber)), device.getMacAddress())) { System.out.println("\nDB Update ExpOver Success"); } else { System.out.println("\nDB Update ExpOver Failed"); } } } else if (action.compareTo(Constants.acknowledgement) == 0) { System.out.println("\nAcknowledgement Received -->"); int expNumber = Integer.parseInt(jsonMap.get(Constants.experimentNumber)); System.out.println("\nExperiment number : " + expNumber); //int sessionId = Utils.getCurrentSessionID(); int expId = 1; ///important int expId =1;// Utils.getCurrentExperimentID(Integer.toString(1)); System.out.println("\nExperiment number : " + expNumber + "== " + expId); // if (expNumber == expId) { if (macAddress != null && !macAddress.equals("")) { DeviceInfo device = session.connectedClients.get(macAddress); session.actualFilteredDevices.add(device); System.out.println("\n Ack : " + expNumber + " Acknowledgement Received!!!"); if (DBManager.updateControlFileSendStatus(expNumber, macAddress, 1, "Successfully sent Control File")) { System.out.println("\n Ack : " + expNumber + " DB updated Successfully"); } else { System.out.println("\n Ack : " + expNumber + " DB updation Failed"); } ///important Utils.addExperimentDetails(expId, device, false); } // } // update the db. } else { System.out.println("\n[" + tid + "] Some Other Operation..."); } newConnection = false; } } catch (Exception ex) { System.out.println("Json Ex : " + ex.toString()); } } try { Thread.sleep(5000); // wait for interrupt } catch (InterruptedException ex) { System.out.println("\n[" + tid + "] InterruptedException 1 : " + ex.toString() + "\n"); try { sock.close(); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException5 : " + ex1.toString() + "\n"); } break; // } } } catch (IOException ex) { System.out.println("\n [" + tid + "] IOException1 : " + ex.toString() + "\n"); try { sock.close(); // session.connectedClients.remove(conn); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException2 : " + ex1.toString() + "\n"); } } catch (Exception ex) { System.out.println("\n[" + tid + "] IOException3 : " + ex.toString() + "\n"); try { sock.close(); // session.connectedClients.remove(conn); } catch (IOException ex1) { System.out.println("\n[" + tid + "] IOException4 : " + ex1.toString() + "\n"); } } }