Java Code Examples for java.net.InetAddress.getHostAddress()

The following are Jave code examples for showing how to use getHostAddress() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: ZooKeeper   File: ConnectionBean.java   Source Code and License Vote up 7 votes
public ConnectionBean(ServerCnxn connection,ZooKeeperServer zk){
    this.connection = connection;
    this.stats = connection;
    this.zk = zk;
    
    InetSocketAddress sockAddr = connection.getRemoteSocketAddress();
    if (sockAddr == null) {
        remoteIP = "Unknown";
    } else {
        InetAddress addr = sockAddr.getAddress();
        if (addr instanceof Inet6Address) {
            remoteIP = ObjectName.quote(addr.getHostAddress());
        } else {
            remoteIP = addr.getHostAddress();
        }
    }
    sessionId = connection.getSessionId();
}
 
Example 2
Project: jdk8u-jdk   File: TCPTransport.java   Source Code and License Vote up 6 votes
/**
 * Verify that the given AccessControlContext has permission to
 * accept this connection.
 */
void checkAcceptPermission(SecurityManager sm,
                           AccessControlContext acc)
{
    /*
     * Note: no need to synchronize on cache-related fields, since this
     * method only gets called from the ConnectionHandler's thread.
     */
    if (sm != cacheSecurityManager) {
        okContext = null;
        authCache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = sm;
    }
    if (acc.equals(okContext) || authCache.containsKey(acc)) {
        return;
    }
    InetAddress addr = socket.getInetAddress();
    String host = (addr != null) ? addr.getHostAddress() : "*";

    sm.checkAccept(host, socket.getPort());

    authCache.put(acc, new SoftReference<AccessControlContext>(acc));
    okContext = acc;
}
 
Example 3
Project: WifiChatSharing   File: MessageActivity.java   Source Code and License Vote up 6 votes
private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {

            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();

            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}
 
Example 4
Project: JinsMemeBRIDGE-Android   File: MemeOSC.java   Source Code and License Vote up 6 votes
public static String getRemoteIPv4Address() {
  try {
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface ni : interfaces) {
      List<InetAddress> addresses = Collections.list(ni.getInetAddresses());
      for (InetAddress addr : addresses) {
        if (!addr.isLoopbackAddress()) {
          String strAddr = addr.getHostAddress();
          if(!strAddr.contains(":")) {
            return strAddr.substring(0, strAddr.lastIndexOf(".") + 1) + "255";
          }
        }
      }
    }
  } catch (SocketException e) {
    e.printStackTrace();
  }

  return "255.255.255.255";
}
 
Example 5
Project: https-github.com-apache-zookeeper   File: StaticHostProvider.java   Source Code and License Vote up 6 votes
private List<InetSocketAddress> resolveAndShuffle(Collection<InetSocketAddress> serverAddresses) {
    List<InetSocketAddress> tmpList = new ArrayList<InetSocketAddress>(serverAddresses.size());       
    for (InetSocketAddress address : serverAddresses) {
        try {
            InetAddress ia = address.getAddress();
            String addr = (ia != null) ? ia.getHostAddress() : address.getHostString();
            InetAddress resolvedAddresses[] = InetAddress.getAllByName(addr);
            for (InetAddress resolvedAddress : resolvedAddresses) {
                InetAddress taddr = InetAddress.getByAddress(address.getHostString(), resolvedAddress.getAddress());
                tmpList.add(new InetSocketAddress(taddr, address.getPort()));
            }
        } catch (UnknownHostException ex) {
            LOG.warn("No IP address found for server: {}", address, ex);
        }
    }
    Collections.shuffle(tmpList, sourceOfRandomness);
    return tmpList;
}
 
Example 6
Project: fuck_zookeeper   File: ConnectionBean.java   Source Code and License Vote up 6 votes
public ConnectionBean(ServerCnxn connection,ZooKeeperServer zk){
    this.connection = connection;
    this.stats = connection;
    this.zk = zk;
    
    InetSocketAddress sockAddr = connection.getRemoteSocketAddress();
    if (sockAddr == null) {
        remoteIP = "Unknown";
    } else {
        InetAddress addr = sockAddr.getAddress();
        if (addr instanceof Inet6Address) {
            remoteIP = ObjectName.quote(addr.getHostAddress());
        } else {
            remoteIP = addr.getHostAddress();
        }
    }
    sessionId = connection.getSessionId();
}
 
Example 7
Project: reading-and-annotate-rocketmq-3.4.6   File: ChannelUtil.java   Source Code and License Vote up 5 votes
public static String getRemoteIp(Channel channel) {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
    if (inetSocketAddress == null) {
        return "";
    }
    final InetAddress inetAddr = inetSocketAddress.getAddress();
    return (inetAddr != null ? inetAddr.getHostAddress() : inetSocketAddress.getHostName());
}
 
Example 8
Project: jdk8u-jdk   File: ChangeHostName.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws Exception {

        InetAddress localAddress = InetAddress.getLocalHost();
        String[] hostlist = new String[] {
            localAddress.getHostAddress(), localAddress.getHostName() };

        for (int i = 0; i < hostlist.length; i++) {

            System.setProperty("java.rmi.server.hostname", hostlist[i]);
            Remote impl = new ChangeHostName();
            System.err.println("\ncreated impl extending URO: " + impl);

            Receiver stub = (Receiver) RemoteObject.toStub(impl);
            System.err.println("stub for impl: " + stub);

            System.err.println("invoking method on stub");
            stub.receive(stub);

            UnicastRemoteObject.unexportObject(impl, true);
            System.err.println("unexported impl");

            if (stub.toString().indexOf(hostlist[i]) >= 0) {
                System.err.println("stub's ref contains hostname: " +
                                   hostlist[i]);
            } else {
                throw new RuntimeException(
                    "TEST FAILED: stub's ref doesn't contain hostname: " +
                    hostlist[i]);
            }
        }
        System.err.println("TEST PASSED");
    }
 
Example 9
Project: otter-G   File: AddressUtils.java   Source Code and License Vote up 5 votes
private static boolean isValidHostAddress(InetAddress address) {
    if (address == null || address.isLoopbackAddress()) {
        return false;
    }

    String name = address.getHostAddress();
    return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name) && IP_PATTERN.matcher(name)
        .matches());
}
 
Example 10
Project: BiglyBT   File: BuddyPluginTracker.java   Source Code and License Vote up 5 votes
protected void
updateIP()
{
	InetAddress	latest_ip = buddy.getAdjustedIP();

	if ( latest_ip != null ){

		current_ip	= latest_ip.getHostAddress();

		log( "IP set to " + current_ip );
	}
}
 
Example 11
Project: lib-commons-httpclient   File: SimpleHttpServer.java   Source Code and License Vote up 5 votes
/**
 * Returns the IP address that this HTTP server instance is bound to.
 * @return String representation of the IP address or <code>null</code> if not running
 */
public String getLocalAddress() {
    InetAddress address = listener.getInetAddress();
    // Ugly work-around for older JDKs
    byte[] octets = address.getAddress();
    if ((octets[0] == 0) 
     && (octets[1] == 0) 
     && (octets[2] == 0) 
     && (octets[3] == 0)) {
        return "localhost"; 
    } else {
        return address.getHostAddress();
    }
}
 
Example 12
Project: Backmemed   File: LanServerDetector.java   Source Code and License Vote up 5 votes
public synchronized void addServer(String pingResponse, InetAddress ipAddress)
{
    String s = ThreadLanServerPing.getMotdFromPingResponse(pingResponse);
    String s1 = ThreadLanServerPing.getAdFromPingResponse(pingResponse);

    if (s1 != null)
    {
        s1 = ipAddress.getHostAddress() + ":" + s1;
        boolean flag = false;

        for (LanServerInfo lanserverinfo : this.listOfLanServers)
        {
            if (lanserverinfo.getServerIpPort().equals(s1))
            {
                lanserverinfo.updateLastSeen();
                flag = true;
                break;
            }
        }

        if (!flag)
        {
            this.listOfLanServers.add(new LanServerInfo(s, s1));
            this.wasUpdated = true;
        }
    }
}
 
Example 13
Project: L2J-Global   File: L2LoginClient.java   Source Code and License Vote up 5 votes
@Override
public String toString()
{
	final InetAddress address = getConnection().getInetAddress();
	if (getState() == LoginClientState.AUTHED_LOGIN)
	{
		return "[" + getAccount() + " (" + (address == null ? "disconnected" : address.getHostAddress()) + ")]";
	}
	return "[" + (address == null ? "disconnected" : address.getHostAddress()) + "]";
}
 
Example 14
Project: javase   File: Server.java   Source Code and License Vote up 5 votes
public ClientHandler(Socket socket) {
	this.socket = socket;
	/*
	 * 通过Socket获取远程计算机地址信息 对于服务端而言,远程计算机就是客户端了
	 */
	InetAddress address = socket.getInetAddress();
	// 获取IP地址
	host = address.getHostAddress();
}
 
Example 15
Project: mumu   File: WebUtil.java   Source Code and License Vote up 5 votes
/**
 * 获取计算机的ip地址
 * @return
 */
public static String getIpAddr() {
	String ipAddress = null;
	try {
		InetAddress address = InetAddress.getLocalHost();
		ipAddress = address.getHostAddress();
	} catch (UnknownHostException e) {
		logger.error(e.getMessage(), e);
	}
	return ipAddress;
}
 
Example 16
Project: openjdk-jdk10   File: SubNetworkInterfaceTest.java   Source Code and License Vote up 5 votes
static void doReverseLookup(NetworkInterface netIf) throws SocketException, UnknownHostException {
    for (NetworkInterface subIf : Collections.list(netIf.getSubInterfaces())) {
        Enumeration<InetAddress> subInetAddresses = subIf.getInetAddresses();
        while (subInetAddresses != null && subInetAddresses.hasMoreElements()) {
            InetAddress inetAddress = subInetAddresses.nextElement();
            String reversalString = inetAddress.getHostAddress();
            //should not throw UHE in case of virtual sub interface
            InetAddress.getByName(reversalString);
        }
    }
}
 
Example 17
Project: My-Blog   File: IPKit.java   Source Code and License Vote up 5 votes
/**
 * @return 本机IPSocketException
 * @throws SocketException
 */
public static String getRealIp() throws SocketException {
    String localip = null;// 本地IP,如果没有配置外网IP则返回它
    String netip = null;// 外网IP

    Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
    InetAddress ip = null;
    boolean finded = false;// 是否找到外网IP
    while (netInterfaces.hasMoreElements() && !finded) {
        NetworkInterface ni = netInterfaces.nextElement();
        Enumeration<InetAddress> address = ni.getInetAddresses();
        while (address.hasMoreElements()) {
            ip = address.nextElement();
            if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 外网IP
                netip = ip.getHostAddress();
                finded = true;
                break;
            } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 内网IP
                localip = ip.getHostAddress();
            }
        }
    }

    if (netip != null && !"".equals(netip)) {
        return netip;
    } else {
        return localip;
    }
}
 
Example 18
Project: nifi-registry   File: RunNiFiRegistry.java   Source Code and License Vote up 5 votes
private String getHostname() {
    String hostname = "Unknown Host";
    String ip = "Unknown IP Address";
    try {
        final InetAddress localhost = InetAddress.getLocalHost();
        hostname = localhost.getHostName();
        ip = localhost.getHostAddress();
    } catch (final Exception e) {
        defaultLogger.warn("Failed to obtain hostname for notification due to:", e);
    }

    return hostname + " (" + ip + ")";
}
 
Example 19
Project: LightSIP   File: MessageProcessor.java   Source Code and License Vote up 5 votes
/**
    * Initializes this MessageProcessor. Needed for extensions
    * that use classloading
    * 
    * @param ipAddress2
    * @param transactionStack
    * @param port2
    */
public final void initialize( InetAddress ipAddress, int port,
		SIPTransactionStack transactionStack ) {
	
	this.sipStack = transactionStack;
       this.savedIpAddress = ipAddress.getHostAddress();
       this.ipAddress = ipAddress;
       this.port = port;
       this.sentByHostPort = new HostPort();
       this.sentByHostPort.setHost(new Host(ipAddress.getHostAddress()));
       this.sentByHostPort.setPort(port);		
}
 
Example 20
Project: hadoop   File: Server.java   Source Code and License Vote up 4 votes
/** Returns remote address as a string when invoked inside an RPC.
 *  Returns null in case of an error.
 */
public static String getRemoteAddress() {
  InetAddress addr = getRemoteIp();
  return (addr == null) ? null : addr.getHostAddress();
}