List of usage examples for java.net InetAddress getByAddress
public static InetAddress getByAddress(byte[] addr) throws UnknownHostException
From source file:org.midonet.cluster.ClusterBgpManagerTest.java
@Test public void testAddAnotherRoute() throws Throwable { final BGP myBgp = new BGP().setPortId(portId).setPeerAddr(IPv4Addr.fromString("192.168.1.1")).setLocalAS(1) .setPeerAS(2);/*from ww w . ja v a2 s . c o m*/ UUID bgpId = bgpMgr.create(myBgp); myBgp.setId(bgpId); final AdRoute[] route = new AdRoute[] { new AdRoute().setPrefixLength((byte) 24) .setNwPrefix(InetAddress.getByAddress(IPv4Addr.stringToBytes("192.168.1.2"))).setBgpId(bgpId) }; clusterBgpManager.adRouteMgr.create(Converter.toAdRouteConfig(route[0])); clusterBgpManager.registerNewBuilder(portId, new FailingBGPListBuilder() { @Override public void addBGP(BGP bgp) { assertEquals(myBgp, bgp); } @Override public void addAdvertisedRoute(AdRoute adRoute) { adRoute.setId(null); assertEquals(route[0], adRoute); } }.expectCalls(3)); route[0] = new AdRoute().setPrefixLength((byte) 24) .setNwPrefix(InetAddress.getByAddress(IPv4Addr.stringToBytes("192.168.1.3"))).setBgpId(bgpId); clusterBgpManager.adRouteMgr.create(Converter.toAdRouteConfig(route[0])); }
From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java
@Override public List<InetAddress> findExistingIPs(final InetAddress startAddr, final InetAddress endAddr) { return getJdbcTemplate().query("select ipaddress from dhcplease" + " where ipaddress >= ? and ipaddress <= ?" + " order by ipaddress", new PreparedStatementSetter() { @Override/*from w w w .ja v a 2s . co m*/ public void setValues(PreparedStatement ps) throws SQLException { ps.setBytes(1, startAddr.getAddress()); ps.setBytes(2, endAddr.getAddress()); } }, new RowMapper<InetAddress>() { @Override public InetAddress mapRow(ResultSet rs, int rowNum) throws SQLException { InetAddress inetAddr = null; try { inetAddr = InetAddress.getByAddress(rs.getBytes("ipaddress")); } catch (UnknownHostException e) { // re-throw as SQLException throw new SQLException("Unable to map ipaddress", e); } return inetAddr; } }); }
From source file:jp.primecloud.auto.common.component.DnsStrategy.java
protected String getHostName(String ipAddress) { byte[] addr = new byte[4]; String[] octets = StringUtils.split(ipAddress, ".", 4); for (int i = 0; i < 4; i++) { addr[i] = (byte) Integer.parseInt(octets[i]); }//from w w w . j ava 2 s. c o m InetAddress address; try { address = InetAddress.getByAddress(addr); return address.getCanonicalHostName(); } catch (UnknownHostException e) { return null; } }
From source file:org.wso2.carbon.apimgt.keymgt.internal.APIKeyMgtServiceComponent.java
/** * Get INetAddress by host name or IP Address * * @param host name or host IP String/*ww w. j a v a 2s. com*/ * @return InetAddress * @throws java.net.UnknownHostException */ private InetAddress getHostAddress(String host) throws UnknownHostException { String[] splittedString = host.split("\\."); boolean value = checkIfIP(splittedString); if (!value) { return InetAddress.getByName(host); } byte[] byteAddress = new byte[4]; for (int i = 0; i < splittedString.length; i++) { if (Integer.parseInt(splittedString[i]) > 127) { byteAddress[i] = Integer.valueOf(Integer.parseInt(splittedString[i]) - 256).byteValue(); } else { byteAddress[i] = Byte.parseByte(splittedString[i]); } } return InetAddress.getByAddress(byteAddress); }
From source file:org.basdroid.common.NetworkUtils.java
public static String getApIpAddr(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifiManager.getDhcpInfo(); byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress); try {/*from w w w. ja v a 2s. c o m*/ String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress(); return apIpAddr; } catch (UnknownHostException e) { e.printStackTrace(); } return null; }
From source file:edu.umass.cs.utils.Util.java
private static InetSocketAddress encodedStringToInetSocketAddress(String str) throws UnknownHostException, UnsupportedEncodingException { byte[] buf = str.getBytes(CHARSET); int port = (int) (buf[buf.length - 2] << 8) + (buf[buf.length - 1] & 255); return new InetSocketAddress(InetAddress.getByAddress(Arrays.copyOfRange(buf, 0, 4)), port); }
From source file:org.midonet.cluster.ClusterBgpManagerTest.java
@Test public void testAddAnotherAndRemoveRoute() throws Throwable { final BGP myBgp = new BGP().setPortId(portId).setPeerAddr(IPv4Addr.fromString("192.168.1.1")).setLocalAS(1) .setPeerAS(2);//w w w .ja v a2 s. c o m UUID bgpId = bgpMgr.create(myBgp); myBgp.setId(bgpId); final AdRoute[] route = new AdRoute[] { new AdRoute().setPrefixLength((byte) 24) .setNwPrefix(InetAddress.getByAddress(IPv4Addr.stringToBytes("192.168.1.2"))).setBgpId(bgpId) }; clusterBgpManager.adRouteMgr.create(Converter.toAdRouteConfig(route[0])); clusterBgpManager.registerNewBuilder(portId, new FailingBGPListBuilder() { @Override public void addBGP(BGP bgp) { assertEquals(myBgp, bgp); } @Override public void addAdvertisedRoute(AdRoute adRoute) { adRoute.setId(null); assertEquals(route[0], adRoute); } @Override public void removeAdvertisedRoute(AdRoute adRoute) { assertEquals(route[0], adRoute); } }.expectCalls(4)); route[0] = new AdRoute().setPrefixLength((byte) 24) .setNwPrefix(InetAddress.getByAddress(IPv4Addr.stringToBytes("192.168.1.3"))).setBgpId(bgpId); route[0].setId(clusterBgpManager.adRouteMgr.create(Converter.toAdRouteConfig(route[0]))); clusterBgpManager.adRouteMgr.delete(route[0].getId()); }
From source file:com.adamkruger.myipaddressinfo.NetworkInfoFragment.java
private static String intToHostAddress(int addressAsInt) { String hostAddress = ""; byte[] ipAddress = BigInteger.valueOf(Integer.reverseBytes(addressAsInt)).toByteArray(); try {// www.j a va 2 s .c o m InetAddress inetAddress = InetAddress.getByAddress(ipAddress); hostAddress = InetAddressToString(inetAddress); } catch (UnknownHostException e) { } return hostAddress; }
From source file:org.javamrt.mrt.BGPFileReader.java
private void parsePeerIndexTable() throws Exception { /*/* ww w .j a va 2s . c o m*/ * System.out.println("in BGPFileReader.parsePeerIndexTable\nheader:"); * RecordAccess.dump(header); System.out.println("record"); * RecordAccess.dump(record); */ // System.err.println("\nin parsePeerIndexTable()..."); /* * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 * 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | * Collector BGP ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | * View Name Length | View Name (variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | * Peer Count | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ int here = 0; // long CollectorBGPId = RecordAccess.getU32 (this.record,here); here += 4; int ViewNameLen = RecordAccess.getU16(this.record, here); here += 2; // String ViewName = null; if (ViewNameLen > 0) { // TODO extract ViewName here += ViewNameLen; } int PeerCount = RecordAccess.getU16(this.record, here); here += 2; /* * System.out.printf("Collector BGP Id: 0x%08X\n",CollectorBGPId); * System.out.printf("View Name Length = %d\n",ViewNameLen); * System.out.printf(" has %d peers\n",PeerCount); */ bgpId = new long[PeerCount]; peerAS = new org.javamrt.mrt.AS[PeerCount]; peerIP = new InetAddress[PeerCount]; for (int i = 0; i < PeerCount; i++) { /* * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 * 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peer Type | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peer BGP ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peer IP address (variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peer AS (variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * The Peer Type field is a bit field which encodes the type of the * AS and IP address as follows: * * Bit 0 - unset for IPv4 Peer IP address, set for IPv6 Bit 1 - * unset when Peer AS field is 16 bits, set when it's 32 bits */ int peerType = RecordAccess.getU8(this.record, here++); bgpId[i] = RecordAccess.getU32(this.record, here); here += 4; if ((peerType & 0x01) == 0) { peerIP[i] = InetAddress.getByAddress(RecordAccess.getBytes(this.record, here, 4)); here += 4; } else { peerIP[i] = InetAddress.getByAddress(RecordAccess.getBytes(this.record, here, 16)); here += 16; } if ((peerType & 0x02) == 0) { peerAS[i] = new AS(RecordAccess.getU16(this.record, here)); here += 2; } else { peerAS[i] = new AS(RecordAccess.getU32(this.record, here)); here += 4; } // System.out.println("Peer "+i+"("+bgpId[i]+"): "+peerIP[i].getHostAddress()+" "+peerAS[i]); } // System.exit(0); }
From source file:com.willhauck.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/*www. j av a 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.JELLY_BEAN_MR2) { 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(); }