Java Code Examples for java.net.InetAddress

The following are top voted examples for showing how to use java.net.InetAddress. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: lettuce   File: TestSettings.java View source code 9 votes vote down vote up
/**
 *
 * @return resolved address of [email protected] #host()}
 * @throws IllegalStateException when hostname cannot be resolved
 */
public static String hostAddr() {
    try {
        InetAddress[] allByName = InetAddress.getAllByName(host());
        for (InetAddress inetAddress : allByName) {
            if (inetAddress instanceof Inet4Address) {
                return inetAddress.getHostAddress();
            }
        }
        return InetAddress.getByName(host()).getHostAddress();
    } catch (UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 2
Project: jentrata-msh   File: AS2Message.java View source code 7 votes vote down vote up
/**
 * Gets the textual representation of the local host.
 * 
 * @return the textual representation of the local host.
 */
private String getLocalHost() {
    try {
        return InetAddress.getLocalHost().getHostAddress();
    }
    catch (Exception e) {
        return "127.0.0.1";
    }
}
 
Example 3
Project: windtalk   File: DNSRecord.java View source code 6 votes vote down vote up
protected Address(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique, int ttl, byte[] rawAddress) {
    super(name, type, recordClass, unique, ttl);
    try {
        this._addr = InetAddress.getByAddress(rawAddress);
    } catch (UnknownHostException exception) {
        logger1.log(Level.WARNING, "Address() exception ", exception);
    }
}
 
Example 4
Project: arduino-android   File: HomeActivity.java View source code 6 votes vote down vote up
public String getLocalIpAddress() 
{
	try 
	{
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
		{
			NetworkInterface intf = en.nextElement();
			for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
			{
				InetAddress inetAddress = enumIpAddr.nextElement();
				if (!inetAddress.isLoopbackAddress()) 
				{
					return inetAddress.getHostAddress().toString();
				}
			}
		}
	} 
	catch (SocketException ex) 
	{
		Log.e("SRM", ex.toString());
	}
	return null;
}
 
Example 5
Project: netlib   File: RouterImpl.java View source code 6 votes vote down vote up
/**
 * can be used to query the exit policies wether this server would allow
 * outgoing connections to the host and port as given in the parameters.
 * <b>IMPORTANT:</b> this routing must be able to work, even if <i>addr</i>
 * is not given!
 * 
 * @param addr
 *            the host that someone wants to connect to
 * @param port
 *            the port that is to be connected to
 * @return a boolean value wether the conenction would be allowed
 */
public boolean exitPolicyAccepts(InetAddress addr, int port) {
    long ip;
    if (addr != null) { // set IP as given
        byte[] temp1 = addr.getAddress();
        long[] temp = new long[4];
        for (int i = 0; i < 4; ++i) {
            temp[i] = temp1[i];
            if (temp[i] < 0)
                temp[i] = 256 + temp[i];
        }
        ;
        ip = ((temp[0] << 24) | (temp[1] << 16) | (temp[2] << 8) | temp[3]);
    } else {
        // HACK: if no IP and port is given, always return true
        if (port == 0)
            return true;
        // HACK: if no IP is given, use only exits that allow ALL ip-ranges
        // this should possibly be replaced by some other way of checking it
        ip = 0xffffffffL;
    }
    ;

    for (int i = 0; i < exitpolicy.length; ++i) {
        if ((exitpolicy[i].getLoPort() <= port)
                && (exitpolicy[i].getHiPort() >= port)
                && (exitpolicy[i].getIp() == (ip & exitpolicy[i].getNetmask()))) {
            return exitpolicy[i].isAccept();
        }
        ;
    }
    ;
    return false;
}
 
Example 6
Project: airlift   File: NodeInfo.java View source code 6 votes vote down vote up
private static boolean isGoodAddress(InetAddress address)
{
    return !address.isAnyLocalAddress() &&
            !address.isLinkLocalAddress() &&
            !address.isLoopbackAddress() &&
            !address.isMulticastAddress();
}
 
Example 7
Project: windtalk   File: HostInfo.java View source code 6 votes vote down vote up
boolean shouldIgnorePacket(DatagramPacket packet) {
    boolean result = false;
    if (this.getInetAddress() != null) {
        InetAddress from = packet.getAddress();
        if (from != null) {
            if (from.isLinkLocalAddress() && (!this.getInetAddress().isLinkLocalAddress())) {
                // Ignore linklocal packets on regular interfaces, unless this is
                // also a linklocal interface. This is to avoid duplicates. This is
                // a terrible hack caused by the lack of an API to get the address
                // of the interface on which the packet was received.
                result = true;
            }
            if (from.isLoopbackAddress() && (!this.getInetAddress().isLoopbackAddress())) {
                // Ignore loopback packets on a regular interface unless this is also a loopback interface.
                result = true;
            }
        }
    }
    return result;
}
 
Example 8
Project: WaarpCommon   File: UUID.java View source code 6 votes vote down vote up
private static int scoreAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress()) {
        return 0;
    }
    if (addr.isMulticastAddress()) {
        return 1;
    }
    if (addr.isLinkLocalAddress()) {
        return 2;
    }
    if (addr.isSiteLocalAddress()) {
        return 3;
    }

    return 4;
}
 
Example 9
Project: appstatus   File: HostPropertyProvider.java View source code 6 votes vote down vote up
public Map<String, String> getProperties() {
	String localhostIp;
	String localhostName;

	try {
		InetAddress addr = InetAddress.getLocalHost();
		localhostIp = addr.getHostAddress();
		localhostName = addr.getCanonicalHostName();
	} catch (UnknownHostException e) {
		localhostIp = "Not available";
		localhostName = "Not available";
	}

	Map<String, String> result = new HashMap<String, String>(3);
	result.put("name", localhostName);
	result.put("ip", localhostIp);

	return result;
}
 
Example 10
Project: GrowControl   File: NetServerConfig.java View source code 6 votes vote down vote up
public InetAddress getInetAddress() throws UnknownHostException {
	final String host = this.getHost();
	if(host == null)
		return null;
	if("127.0.0.1".equals(host) || "localhost".equalsIgnoreCase(host))
		return InetAddress.getLoopbackAddress();
	return InetAddress.getByName(host);
}
 
Example 11
Project: wso2-synapse   File: PassThroughTransportUtils.java View source code 6 votes vote down vote up
/**
 * This method tries to determine the hostname of the given InetAddress without
 * triggering a reverse DNS lookup.  [email protected] java.net.InetAddress#getHostName()}
 * triggers a reverse DNS lookup which can be very costly in cases where reverse
 * DNS fails. Tries to parse a symbolic hostname from [email protected] java.net.InetAddress#toString()},
 * which is documented to return a String of the form "hostname / literal IP address"
 * with 'hostname' blank if not already computed & stored in <code>address</code>.
 * <p/>
 * If the hostname cannot be determined from InetAddress.toString(),
 * the value of [email protected] java.net.InetAddress#getHostAddress()} is returned.
 *
 * @param address The InetAddress whose hostname has to be determined
 * @return hostsname, if it can be determined. hostaddress, if not.          
 */
public static String getHostName(InetAddress address) {
    String result;
    String hostAddress = address.getHostAddress();
    String inetAddr = address.toString();
    int index1 = inetAddr.lastIndexOf('/');
    int index2 = inetAddr.indexOf(hostAddress);
    if (index2 == index1 + 1) {
        if (index1 == 0) {
            result = hostAddress;
        } else {
            result = inetAddr.substring(0, index1);
        }
    } else {
        result = hostAddress;
    }
    return result;
}
 
Example 12
Project: appstatus   File: GooglePingStatusChecker.java View source code 6 votes vote down vote up
public ICheckResult checkStatus() {
	ICheckResult result = null;

	try {
		InetAddress address = InetAddress.getByName("www.google.com");

		if (address.isReachable(2000)) {
			result = createResult(OK);
			result.setDescription("Google Access ok");

		} else {
			throw new Exception("Ping timeout (2000ms)");
		}

	} catch (Exception e) {
		result = createResult(WARN);
		result.setDescription("Google ping failed");
		result.setResolutionSteps("Ping failed. This means that ICMP messages are blocked by this host. (This may not be an issue) "
				+ e.getMessage());

	}

	return result;
}
 
Example 13
Project: j2objc   File: InetAddressTest.java View source code 6 votes vote down vote up
public void test_isNumeric() throws Exception {
    // IPv4
    assertTrue(InetAddress.isNumeric("1.2.3.4"));
    assertTrue(InetAddress.isNumeric("127.0.0.1"));

    // IPv6
    assertTrue(InetAddress.isNumeric("::1"));
    assertTrue(InetAddress.isNumeric("2001:4860:800d::68"));

    // Mapped IPv4
    assertTrue(InetAddress.isNumeric("::ffff:127.0.0.1"));

    // Optional square brackets around IPv6 addresses, including mapped IPv4.
    assertTrue(InetAddress.isNumeric("[2001:4860:800d::68]"));
    assertTrue(InetAddress.isNumeric("[::ffff:127.0.0.1]"));

    // Negative test
    assertFalse(InetAddress.isNumeric("example.com"));

    for (String invalid : INVALID_IPv4_NUMERIC_ADDRESSES) {
        assertFalse(invalid, InetAddress.isNumeric(invalid));
    }
}
 
Example 14
Project: airlift   File: DatabaseIpAddressUtilTest.java View source code 6 votes vote down vote up
private void verifyIpAddressConversion(String ipString, int expectedJavaIpAddress, int expectedDatabaseIpAddress)
        throws UnknownHostException
{
    // use Java to convert the string to an integer
    InetAddress address = InetAddress.getByName(ipString);
    // java inet4 address hashCode is the address object
    int javaIpAddress = address.hashCode();

    // Verify the java integer value is as expected
    assertEquals(javaIpAddress, expectedJavaIpAddress);

    // Convert to database style and verify
    int databaseIpAddress = toDatabaseIpAddress(javaIpAddress);
    assertEquals(databaseIpAddress, expectedDatabaseIpAddress);

    // Finally, round trip back to java and verify
    assertEquals(fromDatabaseIpAddress(databaseIpAddress), javaIpAddress);
}
 
Example 15
Project: property-db   File: VpnProfile.java View source code 6 votes vote down vote up
/**
 * Test if profile is valid for lockdown, which requires IPv4 address for
 * both server and DNS. Server hostnames would require using DNS before
 * connection.
 */
public boolean isValidLockdownProfile() {
    try {
        InetAddress.parseNumericAddress(server);

        for (String dnsServer : dnsServers.split(" +")) {
            InetAddress.parseNumericAddress(this.dnsServers);
        }
        if (TextUtils.isEmpty(dnsServers)) {
            Log.w(TAG, "DNS required");
            return false;
        }

        // Everything checked out above
        return true;

    } catch (IllegalArgumentException e) {
        Log.w(TAG, "Invalid address", e);
        return false;
    }
}
 
Example 16
Project: property-db   File: SocketPermission.java View source code 6 votes vote down vote up
/** [email protected]} 
 * [email protected]}
 * get IP addresses. Sets invalid to true if we can't get them.
 *
 * [email protected]}
 */
void getIP()
    throws UnknownHostException
{
    if (addresses != null || wildcard || invalid) return;

    try {
        // now get all the IP addresses
        String host;
        if (getName().charAt(0) == '[') {
            // Literal IPv6 address
            host = getName().substring(1, getName().indexOf(']'));
        } else {
            int i = getName().indexOf(":");
            if (i == -1)
                host = getName();
            else {
                host = getName().substring(0,i);
            }
        }

        addresses =
            new InetAddress[] {InetAddress.getAllByName0(host, false)[0]};

    } catch (UnknownHostException uhe) {
        invalid = true;
        throw uhe;
    }  catch (IndexOutOfBoundsException iobe) {
        invalid = true;
        throw new UnknownHostException(getName());
    }
}
 
Example 17
Project: reactor   File: UdpServerTests.java View source code 6 votes vote down vote up
private boolean isMulticastEnabledIPv4Interface(NetworkInterface iface) throws SocketException {
	if (!iface.supportsMulticast() || !iface.isUp()) {
		return false;
	}

	for (Enumeration<InetAddress> i = iface.getInetAddresses(); i.hasMoreElements(); ) {
		InetAddress address = i.nextElement();
		if (address.getClass() == Inet4Address.class) {
			return true;
		}
	}

	return false;
}
 
Example 18
Project: jentrata-msh   File: EjbConnection.java View source code 5 votes vote down vote up
/**
 * Connects to the destination URL using the specified username and
 * password.
 * 
 * @param username the username used to connect. null if authentication is
 *            not required.
 * @param password the password used to connect. null if authentication is
 *            not required.
 * @throws EjbConnectionException if errors occurred during the
 *             establishment of connection or, the connection has been
 *             connected or closed already.
 */
public synchronized void connect(String username, String password)
        throws EjbConnectionException {
    if (!connected && !closed) {
        try {
            String[] connStrings = getConnectionStrings();

            Hashtable props = new Hashtable();
            props.put(InitialContext.PROVIDER_URL, connStrings[0]);
            props.put(InitialContext.INITIAL_CONTEXT_FACTORY,
                    connStrings[1]);

            // This establishes the security for
            // authorization/authentication
            if (username != null && !"".equals(username)) {
                props.put(InitialContext.SECURITY_PRINCIPAL, username);
                props.put(InitialContext.SECURITY_CREDENTIALS,
                        password == null ? "" : password);
                if (connStrings.length > 2) {
                    props.put(InitialContext.SECURITY_PROTOCOL,
                            connStrings[2]);
                }
            }

            InetAddress localhost = InetAddress.getLocalHost();
            host = localhost.getHostName() + "@"
                    + localhost.getHostAddress();

            InitialContext context = new InitialContext(props);
            context.rebind(host, "connected");

            initialContext = context;

            connected = true;
            closed = false;
        }
        catch (Exception e) {
            throw new EjbConnectionException(
                    "Unable to establish connection.", e);
        }
    }
    else {
        throw new EjbConnectionException(
                "Connection has been connected or closed already.");
    }
}
 
Example 19
Project: NemoVelo   File: StandardSocketFactory.java View source code 5 votes vote down vote up
public boolean isLocallyConnected(com.mysql.jdbc.ConnectionImpl conn)
		throws SQLException {
	long threadId = conn.getId();
	java.sql.Statement processListStmt = conn.getMetadataSafeStatement();
	ResultSet rs = null;

	try {
		String processHost = null;

		rs = processListStmt.executeQuery("SHOW PROCESSLIST");

		while (rs.next()) {
			long id = rs.getLong(1);

			if (threadId == id) {

				processHost = rs.getString(3);

				break;
			}
		}

		// "inject" for tests
		if (System.getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME) != null) {
			processHost = System
					.getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME);
		} else if (conn.getProperties().getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME) != null) {
			processHost = conn.getProperties().getProperty(IS_LOCAL_HOSTNAME_REPLACEMENT_PROPERTY_NAME);
		}

		if (processHost != null) {
			if (processHost.indexOf(":") != -1) {
				processHost = processHost.split(":")[0];

				try {
					boolean isLocal = false;

					InetAddress whereMysqlThinksIConnectedFrom = InetAddress.getByName(processHost);
					SocketAddress remoteSocketAddr = rawSocket.getRemoteSocketAddress();
					
					if (remoteSocketAddr instanceof InetSocketAddress) {
						InetAddress whereIConnectedTo = ((InetSocketAddress)remoteSocketAddr).getAddress();
						
						isLocal = whereMysqlThinksIConnectedFrom.equals(whereIConnectedTo);
					}
					
					return isLocal;
				} catch (UnknownHostException e) {
					conn.getLog().logWarn(
							Messages.getString(
									"Connection.CantDetectLocalConnect",
									new Object[] { host }), e);

					return false;
				}
			}
		}

		return false;
	} finally {
		processListStmt.close();
	}
}