List of usage examples for java.net InetAddress getByName
public static InetAddress getByName(String host) throws UnknownHostException
From source file:ca.viaware.dlna.ssdp.SSDPService.java
public void run() { try {//from www . j a v a 2s . com this.listener = new MulticastListener(this); this.listener.start(); Searcher searcher = new Searcher(this.outSock); searcher.start(); } catch (IOException e) { e.printStackTrace(); } Thread advertiser = new Thread(new Runnable() { public void send(String data) { try { byte[] bytes = data.getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("239.255.255.250"), 1900); outSock.send(packet); } catch (IOException e) { e.printStackTrace(); } } public void sendNotify(String usn, String nt, String uid) { String http = "NOTIFY * HTTP/1.1\n"; http += baseAnnounce; http += "NT: " + nt + "\r\n"; http += "USN: " + usn + "\r\n"; http += "LOCATION: http://" + httpConfig.getString("host") + ":" + httpConfig.getInt("port") + "/" + uid + "/\r\n"; http += "\r\n"; send(http); } @Override public void run() { while (true) { Log.info("SSDP: Advertising..."); for (int i = 0; i < 3; i++) { for (Device d : DeviceManager.getDevices()) { sendNotify("uuid: " + d.getUid() + "::upnp:rootdevice", "upnp:rootdevice", d.getUid()); sendNotify("uuid:" + d.getUid(), "uuid:" + d.getUid(), d.getUid()); sendNotify( "uuid:" + d.getUid() + "::urn:schemas-upnp-org:device:" + d.getType() + ":" + d.getVersion(), "urn:schemas-upnp-org:device:" + d.getType() + ":" + d.getVersion(), d.getUid()); for (Service s : d.getServices()) { sendNotify( "uuid:" + d.getUid() + "::urn:schemas-upnp-org:service:" + s.getType() + ":" + s.getVersion(), "urn:schemas-upnp-org:service:" + s.getType() + ":" + s.getVersion(), d.getUid()); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(30 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); advertiser.start(); Log.info("Started SSDP Service"); }
From source file:es.us.lsi.restest.engine.UnirestTest.java
private String findAvailableIpAddress() throws IOException { for (int i = 100; i <= 255; i++) { String ip = "192.168.1." + i; if (!InetAddress.getByName(ip).isReachable(1000)) { return ip; }//from w w w.j a v a 2s .c o m } throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); }
From source file:net.pms.network.HTTPServer.java
public boolean start() throws IOException { hostname = configuration.getServerHostname(); InetSocketAddress address;/*from w w w .j av a 2s . co m*/ if (StringUtils.isNotBlank(hostname)) { logger.info("Using forced address " + hostname); InetAddress tempIA = InetAddress.getByName(hostname); if (tempIA != null && networkInterface != null && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) { address = new InetSocketAddress(tempIA, port); } else { address = new InetSocketAddress(hostname, port); } } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface logger.info("Using address {} found on network interface: {}", iafinal, networkInterface.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { logger.info("Using localhost address"); address = new InetSocketAddress(port); } logger.info("Created socket: " + address); if (configuration.isHTTPEngineV2()) { // HTTP Engine V2 group = new DefaultChannelGroup("myServer"); factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group); bootstrap.setPipelineFactory(pipeline); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("reuseAddress", true); bootstrap.setOption("child.reuseAddress", true); bootstrap.setOption("child.sendBufferSize", 65536); bootstrap.setOption("child.receiveBufferSize", 65536); channel = bootstrap.bind(address); group.add(channel); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } } else { // HTTP Engine V1 serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } runnable = new Thread(this, "HTTP Server"); runnable.setDaemon(false); runnable.start(); } return true; }
From source file:amplify.NTPClient.java
/** * Process <code>TimeInfo</code> object and print its details. * * @param info <code>TimeInfo</code> object. *///from w ww .j a va 2 s . com public static void processResponse(TimeInfo info) { NtpV3Packet message = info.getMessage(); int stratum = message.getStratum(); String refType; if (stratum <= 0) refType = "(Unspecified or Unavailable)"; else if (stratum == 1) refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc. else refType = "(Secondary Reference; e.g. via NTP or SNTP)"; // stratum should be 0..15... System.out.println(" Stratum: " + stratum + " " + refType); int version = message.getVersion(); int li = message.getLeapIndicator(); System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision()); System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")"); int poll = message.getPoll(); // poll value typically btwn MINPOLL (4) and MAXPOLL (14) System.out.println( " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")"); double disp = message.getRootDispersionInMillisDouble(); System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp)); int refId = message.getReferenceId(); String refAddr = NtpUtils.getHostAddress(refId); String refName = null; if (refId != 0) { if (refAddr.equals("127.127.1.0")) { refName = "LOCAL"; // This is the ref address for the Local Clock } else if (stratum >= 2) { // If reference id has 127.127 prefix then it uses its own reference clock // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5 // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution. if (!refAddr.startsWith("127.127")) { try { InetAddress addr = InetAddress.getByName(refAddr); String name = addr.getHostName(); if (name != null && !name.equals(refAddr)) refName = name; } catch (UnknownHostException e) { // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2) // ref not valid host maybe it's a reference clock name? // otherwise just show the ref IP address. refName = NtpUtils.getReferenceClock(message); } } } else if (version >= 3 && (stratum == 0 || stratum == 1)) { refName = NtpUtils.getReferenceClock(message); // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.) } // otherwise give up on naming the beast... } if (refName != null && refName.length() > 1) refAddr += " (" + refName + ")"; TimeStamp refNtpTime = message.getReferenceTimeStamp(); // Originate Time is time request sent by client (t1) TimeStamp origNtpTime = message.getOriginateTimeStamp(); long destTime = info.getReturnTime(); long localDestTime = System.currentTimeMillis(); // Receive Time is time request received by server (t2) TimeStamp rcvNtpTime = message.getReceiveTimeStamp(); // Transmit time is time reply sent by server (t3) TimeStamp xmitNtpTime = message.getTransmitTimeStamp(); // Destination time is time reply received by client (t4) TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime); info.computeDetails(); // compute offset/delay if not already done Long offsetValue = info.getOffset(); Long delayValue = info.getDelay(); String delay = (delayValue == null) ? "N/A" : delayValue.toString(); String offset = (offsetValue == null) ? "N/A" : offsetValue.toString(); clockOffset = offsetValue != null ? offsetValue.longValue() : 0L; System.out.println(" Reference Identifier:\t" + refAddr); System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString()); System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString()); System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString()); System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString()); System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString()); System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms }
From source file:net.dfs.server.filespace.accessor.impl.WriteSpaceAccessorImpl.java
/** * writeToSPace will write a File object to the newly created local Space. It * makes sure the Space is not null before the File objects are been written to the * Space.//w ww. ja va 2 s . co m * <p> * It returns no value and throws RemoteException or TransactionException on a failure. * * @param file is an object of the type {@link FileStorageModel} */ public void writeToSpace(FileToken token) { if (space == null) { try { if (space == null) { space = spaceCreator.getSpace(InetAddress.getByName(serverIP), InetAddress.getLocalHost()); } } catch (UnknownHostException e) { e.printStackTrace(); } } try { space.write((FileToken) token, null, Long.MAX_VALUE); log.info("Chunk " + token.fileName + " with Chunk No " + token.CHUNK_NO + " Written to the Space"); } catch (RemoteException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } }
From source file:com.mashape.unirest.test.http.UnirestTest.java
private String findAvailableIpAddress() throws UnknownHostException, IOException { for (int i = 100; i <= 255; i++) { String ip = "192.168.1." + i; if (!InetAddress.getByName(ip).isReachable(1000)) { return ip; }/*w w w . j a v a 2 s . c o m*/ } throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); }
From source file:org.transdroid.util.IgnoreTlsSniSocketFactory.java
@Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException { if (autoClose) { // we don't need the plainSocket plainSocket.close();/*from w w w. ja v a 2 s .c o m*/ } SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory .getDefault(0); // For self-signed certificates use a custom trust manager sslSocketFactory.setTrustManagers(new TrustManager[] { new IgnoreSSLTrustManager() }); // create and connect SSL socket, but don't do hostname/certificate verification yet SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port); // enable TLSv1.1/1.2 if available ssl.setEnabledProtocols(ssl.getSupportedProtocols()); // set up SNI before the handshake if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { sslSocketFactory.setHostname(ssl, host); } else { try { java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(ssl, host); } catch (Exception e) { throw new IOException("SNI not usable: " + e, e); } } return ssl; }
From source file:com.myJava.file.driver.remote.ftp.FTPClient.java
public int pasv() throws IOException { int passiveReturnCode = super.pasv(); if (passiveReturnCode == FTPReply.ENTERING_PASSIVE_MODE) { // Parse and display reply host and port in passive mode // It's quite ugly but there is no entry point in apache's ftp library to perform this check. String reply = getReplyStrings()[0]; int i, index, lastIndex; String octet1, octet2;//from w ww . j a v a 2s. c o m StringBuffer host; reply = reply.substring(reply.indexOf('(') + 1, reply.indexOf(')')).trim(); host = new StringBuffer(24); lastIndex = 0; index = reply.indexOf(','); host.append(reply.substring(lastIndex, index)); for (i = 0; i < 3; i++) { host.append('.'); lastIndex = index + 1; index = reply.indexOf(',', lastIndex); host.append(reply.substring(lastIndex, index)); } lastIndex = index + 1; index = reply.indexOf(',', lastIndex); octet1 = reply.substring(lastIndex, index); octet2 = reply.substring(index + 1); // index and lastIndex now used as temporaries try { index = Integer.parseInt(octet1); lastIndex = Integer.parseInt(octet2); } catch (NumberFormatException e) { throw new MalformedServerReplyException( "Could not parse passive host information.\nServer Reply: " + reply); } index <<= 8; index |= lastIndex; String passvHost = host.toString(); //int passvPort = index; //Logger.defaultLogger().info("Passive host received from server : " + passvHost + ":" + passvPort); InetAddress refAddress = InetAddress.getByName(passvHost); if (!refAddress.equals(this._socket_.getInetAddress())) { String msg = "Passive address (" + refAddress + ") differs from host address (" + this._socket_.getInetAddress() + "). This is probably because your server is behind a router. Please check your FTP server's configuration. (for instance, use a masquerade address)"; Logger.defaultLogger().warn(msg); if (!ignorePasvErrors) { throw new IOException(msg); } } } return passiveReturnCode; }
From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java
public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException { this.server = server; this.port = port; try {//from w w w.j a va 2s. c o m if (keyStorePath == null) { throw new IOException("Key store not configured"); } if (server == null) { throw new IOException("Server address not configured"); } keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStorePath), null); TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); SSLSocketFactory socketFactory = context.getSocketFactory(); socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout); socket.setSoTimeout(timeout); sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true); sslSocket.setUseClientMode(true); sslSocket.startHandshake(); output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream())); input = new DataInputStream(sslSocket.getInputStream()); logger.info("Connected to " + server + ":" + port); } catch (IOException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.bigdata.dastor.client.RingCache.java
public void refreshEndPointMap() { for (String seed : seeds_) { try {/* w w w . j av a2s.c o m*/ TSocket socket = new TSocket(seed, port_); TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false); Dastor.Client client = new Dastor.Client(binaryProtocol); socket.open(); Map<String, String> tokenToHostMap = (Map<String, String>) JSONValue .parse(client.get_string_property(DastorThriftServer.TOKEN_MAP)); BiMap<Token, InetAddress> tokenEndpointMap = HashBiMap.create(); for (Map.Entry<String, String> entry : tokenToHostMap.entrySet()) { Token token = StorageService.getPartitioner().getTokenFactory().fromString(entry.getKey()); String host = entry.getValue(); try { tokenEndpointMap.put(token, InetAddress.getByName(host)); } catch (UnknownHostException e) { throw new AssertionError(e); // host strings are IPs } } tokenMetadata = new TokenMetadata(tokenEndpointMap); break; } catch (TException e) { /* let the Exception go and try another seed. log this though */ logger_.debug("Error contacting seed " + seed + " " + e.getMessage()); } } }