List of usage examples for java.net InetAddress getByAddress
public static InetAddress getByAddress(byte[] addr) throws UnknownHostException
From source file:edu.uga.cs.fluxbuster.clustering.DomainCluster.java
/** * Gets the CIDR /24 prefixes of a set of IPv4 addresses * * @param ips the set of ip addresses//from ww w .ja v a2 s . co m * @return the set of /24 prefixes */ private Set<InetAddress> getPrefixes24(Set<InetAddress> ips) { HashSet<InetAddress> retval = new HashSet<InetAddress>(); Set<Inet4Address> ipsv4 = IPDiversityCalculator.getV4Ips(ips); for (Inet4Address ip : ipsv4) { byte[] temp = ip.getAddress(); temp[3] = 0; try { retval.add(InetAddress.getByAddress(temp)); } catch (UnknownHostException e) { if (log.isErrorEnabled()) { log.error("Error getting CIDR /24 prefix", e); } } } return retval; }
From source file:com.harshad.linconnectclient.SettingsActivity.java
@SuppressLint("SimpleDateFormat") private void setupSimplePreferencesScreen() { // Load preferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this); // Add preferences from XML addPreferencesFromResource(R.xml.pref_general); bindPreferenceSummaryToValue(findPreference("pref_ip")); // Preference Categories serverCategory = ((PreferenceCategory) findPreference("cat_servers")); // Preferences refreshPreference = ((Preference) findPreference("pref_refresh")); serverCategory.removePreference(refreshPreference); loadingPreference = ((Preference) findPreference("pref_loading")); serverCategory.removePreference(loadingPreference); Preference prefEnable = findPreference("pref_enable"); prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override//from ww w.j a va 2 s.c om public boolean onPreferenceClick(Preference arg0) { // If Android 4.3+, open Notification Listener settings, // otherwise open accessibility settings if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0); } else { Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"); startActivity(intent); } return true; } }); ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference arg0, Object arg1) { // Update Custom IP address summary arg0.setSummary((String) arg1); refreshServerList(); // Create and send test notification SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss"); Object[] notif = new Object[3]; notif[0] = "Hello from Android!"; notif[1] = "Test succesful @ " + sf.format(new Date()); notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher); new TestTask().execute(notif); return true; } }); Preference prefDownload = findPreference("pref_download"); prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { // Create share dialog with server download URL Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Download LinConnect server @ https://github.com/hauckwill/linconnect-server"); sendIntent.setType("text/plain"); startActivity(sendIntent); return true; } }); Preference prefApplication = findPreference("pref_application"); prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { // Open application settings screen Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class); startActivity(intent); return true; } }); // Preference prefDonateBitcoin = findPreference("pref_donate_btc"); // prefDonateBitcoin // .setOnPreferenceClickListener(new OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference arg0) { // try { // Open installed Bitcoin wallet if possible // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri // .parse("bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect")); // startActivity(intent); // } catch (Exception e) { // Otherwise, show dialog with Bitcoin address // EditText input = new EditText(SettingsActivity.this); // input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo"); // input.setEnabled(false); // new AlertDialog.Builder(SettingsActivity.this) // .setTitle("Bitcoin Address") // .setMessage( // "Please donate to the following Bitcoin address. Thank you for the support.") // .setView(input) // .setPositiveButton( // "Copy Address", // new DialogInterface.OnClickListener() { // public void onClick( // DialogInterface dialog, // int whichButton) { // android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // clipboard // .setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo"); // } // }) // .setNegativeButton( // "Okay", // new DialogInterface.OnClickListener() { // public void onClick( // DialogInterface dialog, // int whichButton) { // } // }).show(); // } // return true; // } // }); // Preference prefGooglePlus = findPreference("pref_google_plus"); // prefGooglePlus // .setOnPreferenceClickListener(new OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference arg0) { // // Open Google Plus page // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri // .parse("https://plus.google.com/114633032648182423928/posts")); // startActivity(intent); // return true; // } // }); // Preference prefDonatePlay = findPreference("pref_donate_play"); // prefDonatePlay // .setOnPreferenceClickListener(new OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference arg0) { // Open Donation Key app on Play Store // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri // .parse("market://details?id=com.willhauck.donation")); // startActivity(intent); // return true; // } // }); // Create handler to process a detected server serverFoundHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.obj != null) { javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj); // Get info about server String name = serviceInfo.getName(); String port = String.valueOf(serviceInfo.getPort()); String ip = serviceInfo.getHostAddresses()[0]; // Create a preference representing the server Preference p = new Preference(SettingsActivity.this); p.setTitle(name); p.setSummary(ip + ":" + port); p.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { refreshServerList(); // Save IP address in preferences Editor e = sharedPreferences.edit(); e.putString("pref_ip", arg0.getSummary().toString()); e.apply(); // Create and send test notification SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss"); Object[] notif = new Object[3]; notif[0] = "Hello from Android!"; notif[1] = "Test succesful @ " + sf.format(new Date()); notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher); new TestTask().execute(notif); return true; } }); // Add preference to server list if it doesn't already exist boolean found = false; for (int i = 0; i < serverCategory.getPreferenceCount(); i++) { if (serverCategory.getPreference(i) != null && serverCategory.getPreference(i).getTitle() != null && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) { found = true; } } if (!found) { serverCategory.addPreference(p); } refreshServerList(); // Remove loading indicator, add refresh indicator if it // isn't already there if (findPreference("pref_loading") != null) serverCategory.removePreference(findPreference("pref_loading")); if (findPreference("pref_refresh") == null) serverCategory.addPreference(refreshPreference); } return true; } }); // Create task to scan for servers class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> { @Override protected void onPreExecute() { // Remove refresh preference, add loading preference if (findPreference("pref_refresh") != null) serverCategory.removePreference(refreshPreference); serverCategory.addPreference(loadingPreference); try { mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener); } catch (Exception e) { } refreshServerList(); } @Override protected Boolean doInBackground(String... notif) { WifiInfo wifiinfo = mWifiManager.getConnectionInfo(); int intaddr = wifiinfo.getIpAddress(); // Ensure there is an active Wifi connection if (intaddr != 0) { byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff), (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) }; InetAddress addr = null; try { addr = InetAddress.getByAddress(byteaddr); } catch (UnknownHostException e1) { } // Create Multicast lock (required for JmDNS) mMulticastLock = mWifiManager.createMulticastLock("LinConnect"); mMulticastLock.setReferenceCounted(true); mMulticastLock.acquire(); try { mJmDNS = JmDNS.create(addr, "LinConnect"); } catch (IOException e) { } // Create listener for detected servers ServerListener = new ServiceListener() { @Override public void serviceAdded(ServiceEvent arg0) { final String name = arg0.getName(); // Send the server data to the handler, delayed by // 500ms to ensure all information is read serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name), 500); } @Override public void serviceRemoved(ServiceEvent arg0) { } @Override public void serviceResolved(ServiceEvent arg0) { mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1); } }; mJmDNS.addServiceListener(jmDnsServiceType, ServerListener); return true; } return false; } @Override protected void onPostExecute(Boolean result) { if (!result) { // Notify user if there is no connection if (findPreference("pref_loading") != null) { serverCategory.removePreference(findPreference("pref_loading")); serverCategory.addPreference(refreshPreference); } Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show(); } } } refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { new ServerScanTask().execute(); return true; } }); // Start scanning for servers new ServerScanTask().execute(); }
From source file:org.apache.cassandra.db.clock.IncrementCounterContext.java
/** * Human-readable String from context.//from w w w . java2s . com * * @param context * version context. * @return a human-readable String of the context. */ public String toString(byte[] context) { context = sortElementsById(context); StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append(FBUtilities.byteArrayToLong(context, 0)); sb.append(", "); sb.append(FBUtilities.byteArrayToLong(context, TIMESTAMP_LENGTH)); sb.append(" + ["); for (int offset = HEADER_LENGTH; offset < context.length; offset += stepLength) { if (offset != HEADER_LENGTH) { sb.append(","); } sb.append("("); try { InetAddress address = InetAddress .getByAddress(ArrayUtils.subarray(context, offset, offset + idLength)); sb.append(address.getHostAddress()); } catch (UnknownHostException uhe) { sb.append("?.?.?.?"); } sb.append(", "); sb.append(FBUtilities.byteArrayToLong(context, offset + idLength)); sb.append(")"); } sb.append("]}"); return sb.toString(); }
From source file:edu.umass.cs.utils.Util.java
private static void testToBytesAndBack() throws UnknownHostException, UnsupportedEncodingException { InetSocketAddress isa = new InetSocketAddress("128.119.235.43", 23451); assert (Util.encodedStringToInetSocketAddress(Util.sockAddrToEncodedString(isa)).equals(isa)); int n = 10000; for (int i = 0; i < n; i++) { long t = (long) (Math.random() * Long.MAX_VALUE); byte[] buf = (Util.longToBytes(t)); assert (t == Util.bytesToLong(buf)); }/* w ww. j a v a 2s . c o m*/ for (int i = 0; i < n; i++) { long value = (long) (Math.random() * Long.MAX_VALUE); assert (value == Util.encodedStringToLong(Util.longToEncodedString(value))); } for (int i = 0; i < n; i++) { byte[] address = new byte[4]; for (int j = 0; j < 4; j++) address[j] = (byte) (Math.random() * Byte.MAX_VALUE); InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByAddress(address), (int) (Math.random() * Short.MAX_VALUE)); assert (Util.encodedStringToInetSocketAddress(Util.sockAddrToEncodedString(sockAddr)).equals(sockAddr)); } }
From source file:org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent.java
/** * Get INetAddress by host name or IP Address * * @param host name or host IP String//from w w w . j a va 2s . c o m * @return InetAddress * @throws UnknownHostException */ private InetAddress getHostAddress(String host) throws UnknownHostException { String[] splittedString = host.split("\\."); if (splittedString.length == 4) { // check whether this is ip address or not. try { Integer.parseInt(splittedString[0]); Integer.parseInt(splittedString[1]); Integer.parseInt(splittedString[2]); Integer.parseInt(splittedString[3]); byte[] byteAddress = new byte[4]; for (int i = 0; i < splittedString.length; i++) { if (Integer.parseInt(splittedString[i]) > 127) { byteAddress[i] = new Integer(Integer.parseInt(splittedString[i]) - 256).byteValue(); } else { byteAddress[i] = Byte.parseByte(splittedString[i]); } } return InetAddress.getByAddress(byteAddress); } catch (Exception e) { log.debug(e); // ignore. } } // if not ip address return host name return InetAddress.getByName(host); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * // w ww . ja va2 s.c o m * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:com.twineworks.kettle.ruby.step.execmodels.SimpleExecutionModel.java
private InetAddress toInetAddress(int addr) { try {// w w w . j a v a 2 s . c o m return InetAddress.getByAddress(toIPByteArray(addr)); } catch (UnknownHostException e) { //should never happen return null; } }
From source file:org.javamrt.mrt.BGPFileReader.java
private MRTRecord parseBgp4Update(int asSize) throws Exception { // Bgp4Update update; // TODO reconocer los AS de 4 bytes aqu int offset = 0; AS srcAs = new AS(RecordAccess.getUINT(record, offset, asSize)); offset = asSize;// w w w. java 2s . com AS dstAs = new AS(RecordAccess.getUINT(record, offset, asSize)); offset += asSize; int iface = RecordAccess.getU16(record, offset); offset += 2; int afi = RecordAccess.getU16(record, offset); offset += 2; // int offset = 2 * asSize + 4; int addrSize = (afi == MRTConstants.AFI_IPv4) ? 4 : 16; InetAddress srcIP = InetAddress.getByAddress(RecordAccess.getBytes(record, offset, addrSize)); offset += addrSize; InetAddress dstIP = InetAddress.getByAddress(RecordAccess.getBytes(record, offset, addrSize)); offset += addrSize; /* * skip the following 16 bytes which are the signature of the BGP header */ offset += 16; int bgpSize = RecordAccess.getU16(record, offset); offset += 2; int bgpType = RecordAccess.getU8(record, offset); offset++; if (Debug.compileDebug) { Debug.printf("Bgp4Update(asSize = %d)\n", asSize); Debug.printf("AS srcAs = %s\n", srcAs.toString()); Debug.printf("AS dstAs = %s\n", dstAs.toString()); Debug.printf("int iface = %d\n", iface); Debug.printf("int Afi = %d\n", afi); Debug.printf("int addrSize = %d\n", addrSize); Debug.println("srcIP = " + srcIP.getHostAddress()); Debug.println("dstIP = " + dstIP.getHostAddress()); Debug.printf("bgpSize = %d\n", bgpSize); Debug.println("bgpType = " + MRTConstants.bgpType(bgpType)); Debug.dump(record); } switch (bgpType) { case MRTConstants.BGP4MSG_KEEPALIVE: return new KeepAlive(header, record); case MRTConstants.BGP4MSG_OPEN: return new Open(header, record); case MRTConstants.BGP4MSG_NOTIFICATION: return new Notification(header, record); case MRTConstants.BGP4MSG_UPDATE: break; // to continue after case() case MRTConstants.BGP4MSG_REFRESH: return new Refresh(header, record); default: throw new Exception("Unknown BGP4 record type(" + bgpType + ")"); } /* * Here is where the update starts */ int unfeasibleLen = RecordAccess.getU16(record, offset); offset += 2; if (Debug.compileDebug) Debug.printf("int unfeasibleLen = %d\n", unfeasibleLen); for (int i = 0; i < unfeasibleLen;) { Nlri wNlri = new Nlri(record, offset, afi); offset += wNlri.getOffset(); i += wNlri.getOffset(); recordFifo.add(new Withdraw(header, srcIP, srcAs, wNlri.toPrefix())); } int attrLen = RecordAccess.getU16(record, offset); if (Debug.compileDebug) Debug.printf("attrLen = %d, offset =%d (%d)\n", attrLen, offset, offset + attrLen + 2); offset += 2; if (attrLen > 0) { Attributes attributes = null; try { attributes = new Attributes(record, attrLen, offset, asSize); } catch (RFC4893Exception rfce) { // // piggyback peer and time info // rfce.setTimestamp(this.time); rfce.setPeer(srcIP); rfce.setAS(srcAs); throw rfce; } catch (Exception e) { throw e; } // // Process MP_REACH and MP_UNREACH // MpUnReach mpUnreach = (MpUnReach) attributes.getAttribute(MRTConstants.ATTRIBUTE_MP_UNREACH); if (mpUnreach != null) { for (Nlri mpu : mpUnreach.getNlri()) { recordFifo.add(new Withdraw(header, srcIP, srcAs, mpu.toPrefix())); } } MpReach mpReach = (MpReach) attributes.getAttribute(MRTConstants.ATTRIBUTE_MP_REACH); if (mpReach != null) { if (Debug.compileDebug) Debug.printf("Has MP_REACH (%s)\n", mpReach.getNlri()); for (Nlri mpu : mpReach.getNlri()) { recordFifo.add(new Advertisement(header, srcIP, srcAs, mpu.toPrefix(), attributes)); } } /* * if (mpReach != null || mpUnreach != null) * System.out.println("This is the whole record"); * RecordAccess.dump(record); * System.out.println("These are the attributes"); * RecordAccess.dump(record,offset,attrLen); * System.out.println("int attrLen = "+attrLen); * * throw new Exception("MP_REACH attribute!"); */ offset += attrLen; if (Debug.compileDebug) Debug.debug("offset(%d) record.length (%d)\n", offset, record.length); while (offset < record.length) { Nlri aNlri = new Nlri(record, offset, afi); offset += aNlri.getOffset(); recordFifo.add(new Advertisement(header, srcIP, srcAs, aNlri.toPrefix(), attributes)); } } if (recordFifo.isEmpty()) { if (Debug.compileDebug) if (Debug.doDebug) throw new BGPFileReaderException("recordFifo empty!", record); return null; } return recordFifo.remove(); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Extracts an {@link InetAddress} object from the given datagram packet. The datagram packet must be of the type * <code>TM_ADDRESS_REPLY_PACKET_ID</code>. * //from w w w . j av a2s. c o m * @param packet * the packet to extract the address from * @return the extracted address or <code>null</code> if it could not be extracted */ private static InetAddress extractInetAddress(DatagramPacket packet) { final byte[] data = packet.getData(); if (data == null) { return null; } if (packet.getLength() < PAYLOAD_OFFSET + 8) { return null; } final int len = byteArrayToInteger(data, PAYLOAD_OFFSET); final byte[] addr = new byte[len]; System.arraycopy(data, PAYLOAD_OFFSET + 4, addr, 0, len); InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { return null; } return inetAddress; }
From source file:org.mythtv.client.ui.MainMenuFragment.java
/** * @throws IOException/*from ww w .j ava 2s.c o m*/ */ private void startProbe() throws IOException { Log.v(TAG, "startProbe : enter"); if (zeroConf != null) { stopProbe(); } // figure out our wifi address, otherwise bail WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiinfo = wifi.getConnectionInfo(); int intaddr = wifiinfo.getIpAddress(); byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff), (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) }; InetAddress addr = InetAddress.getByAddress(byteaddr); Log.d(TAG, "startProbe : wifi address=" + addr.toString()); // start multicast lock mLock = wifi.createMulticastLock("mythtv_lock"); mLock.setReferenceCounted(true); mLock.acquire(); zeroConf = JmDNS.create(addr, HOSTNAME); zeroConf.addServiceListener(MYTHTV_FRONTEND_TYPE, this); Log.v(TAG, "startProbe : exit"); }