下面列出了java.net.InetAddress#getHostName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String getNotLoopbackAddress() {
String hostName = null;
Enumeration<NetworkInterface> interfaces;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface nic = interfaces.nextElement();
Enumeration<InetAddress> addresses = nic.getInetAddresses();
while (hostName == null && addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress()) {
hostName = address.getHostName();
}
}
}
} catch (SocketException e) {
logger.error("getNotLoopbackAddress error!", e);
}
return hostName;
}
/**
* Connects to given ip and port using given Proxy server.
*
* @param p
* Proxy to use.
* @param ip
* Machine to connect to.
* @param port
* Port to which to connect.
*/
public SocksSocket(SocksProxyBase p, InetAddress ip, int port)
throws SocksException {
if (p == null) {
throw new SocksException(SocksProxyBase.SOCKS_NO_PROXY);
}
this.proxy = p.copy();
this.remoteIP = ip;
this.remotePort = port;
this.remoteHost = ip.getHostName();
if (proxy.isDirect(remoteIP)) {
doDirect();
} else {
processReply(proxy.connect(ip, port));
}
}
private static NetworkData buildNetworkData(NetworkInterface networkInterface, InetAddress inetAddress)
throws SocketException {
if (isPhysicalNetworkInterface(networkInterface)) {
String hostName = inetAddress != null ? inetAddress.getHostName() : null;
String hostCanonicalName = inetAddress != null ? inetAddress.getCanonicalHostName() : null;
String interfaceName = networkInterface.getName();
String interfaceDisplayName = networkInterface.getDisplayName();
String interfaceHardwareAddress = ByteUtil.toHexadecimal(networkInterface.getHardwareAddress());
List<String> interfaceAddresses = getInterfaceAddresses(networkInterface);
NetworkData networkData = new NetworkData();
networkData.setHostName(hostName);
networkData.setHostCanonicalName(hostCanonicalName);
networkData.setInterfaceName(interfaceName);
networkData.setInterfaceDisplayName(interfaceDisplayName);
networkData.setInterfaceHardwareAddress(interfaceHardwareAddress);
networkData.setInterfaceAddresses(interfaceAddresses);
return networkData;
}
return null;
}
/**
* parse {@link InetSocketAddress} to get address (format [ip:port])
*/
@Test
public void testParseSocketAddressToString() {
String localhostName;
String localIP;
try {
InetAddress inetAddress = InetAddress.getLocalHost();
localhostName = inetAddress.getHostName();
localIP = inetAddress.getHostAddress();
if (null == localIP || StringUtils.isBlank(localIP)) {
return;
}
} catch (UnknownHostException e) {
localhostName = "localhost";
localIP = "127.0.0.1";
}
SocketAddress socketAddress = new InetSocketAddress(localhostName, port);
String res = RemotingUtil.parseSocketAddressToString(socketAddress);
Assert.assertEquals(localIP + ":" + port, res);
}
private static String determineTaskManagerBindAddressByConnectingToResourceManager(
final Configuration configuration,
final HighAvailabilityServices haServices) throws LeaderRetrievalException {
final Duration lookupTimeout = AkkaUtils.getLookupTimeout(configuration);
final InetAddress taskManagerAddress = LeaderRetrievalUtils.findConnectingAddress(
haServices.getResourceManagerLeaderRetriever(),
lookupTimeout);
LOG.info("TaskManager will use hostname/address '{}' ({}) for communication.",
taskManagerAddress.getHostName(), taskManagerAddress.getHostAddress());
HostBindPolicy bindPolicy = HostBindPolicy.fromString(configuration.getString(TaskManagerOptions.HOST_BIND_POLICY));
return bindPolicy == HostBindPolicy.IP ? taskManagerAddress.getHostAddress() : taskManagerAddress.getHostName();
}
public static String getHostName() throws SocketException {
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
return i.getHostName();
}
}
}
throw new SocketException("Failed to get the IP address for the local host");
}
protected String getHostInfo() {
final StringBuilder buf = new StringBuilder();
try {
final InetAddress ia = InetAddress.getLocalHost();
final String hostname = ia.getHostName();
if (StringUtil.isNotBlank(hostname)) {
buf.append(hostname);
}
final String ip = ia.getHostAddress();
if (StringUtil.isNotBlank(ip)) {
if (buf.length() > 0) {
buf.append(" : ");
}
buf.append(ip);
}
} catch (final Exception e) {
// ignore
}
return buf.toString();
}
private String getHostname() {
try {
// Get hostname by textual representation of IP address
InetAddress addr = InetAddress.getLocalHost();
// Get the host name
String hostname = addr.getHostName();
return hostname;
} catch (UnknownHostException e) {
}
return null;
}
/**
* @return
* @Description: 获取机器名
*/
public static String getHostName() throws Exception {
try {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
return hostname;
} catch (UnknownHostException e) {
throw new Exception();
}
}
/**
* @return
*
* @Description: 获取机器名
*/
public static String getHostName() throws Exception {
try {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
return hostname;
} catch (UnknownHostException e) {
throw new Exception(e);
}
}
/**
* Returns the name of the local host.
*
* @return The host name
* @throws UnknownHostException if IP address of a host could not be determined
*/
public static String getHostname() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostName = inetAddress.getHostName();
assertTrue((hostName != null && !hostName.isEmpty()),
"Cannot get hostname");
return hostName;
}
/**
* Returns the name of the local host.
*
* @return The host name
* @throws UnknownHostException if IP address of a host could not be determined
*/
public static String getHostname() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostName = inetAddress.getHostName();
assertTrue((hostName != null && !hostName.isEmpty()),
"Cannot get hostname");
return hostName;
}
@Override
public String getHostName() throws UnknownHostException {
final SocketAddress remoteAddress = ioSession.getRemoteAddress();
if (remoteAddress == null) throw new UnknownHostException();
final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
final InetAddress inetAddress = socketAddress.getAddress();
return inetAddress.getHostName();
}
public String getRemoteHost() {
InetSocketAddress isa = exchange.getRemoteAddress();
if (isa != null) {
InetAddress ia = isa.getAddress();
if (ia != null) {
return ia.getHostName();
}
}
return null;
}
/**
* Returns the name of the local host.
*
* @return The host name
* @throws UnknownHostException if IP address of a host could not be determined
*/
public static String getHostname() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostName = inetAddress.getHostName();
assertTrue((hostName != null && !hostName.isEmpty()),
"Cannot get hostname");
return hostName;
}
public static String getLocalHostname() {
InetAddress address;
String hostname;
try {
address = InetAddress.getLocalHost();
// force a best effort reverse DNS lookup
hostname = address.getHostName();
if (StringUtil.isEmpty(hostname)) {
hostname = address.toString();
}
} catch (UnknownHostException noIpAddrException) {
hostname = LOCALHOST;
}
return hostname;
}
/**
* Returns the name of the local host.
*
* @return The host name
* @throws UnknownHostException if IP address of a host could not be determined
*/
public static String getHostname() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostName = inetAddress.getHostName();
assertTrue((hostName != null && !hostName.isEmpty()),
"Cannot get hostname");
return hostName;
}
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");
}
/**
* @param address
* IP address to bind
* @param dns
* JmDNS instance
* @param jmdnsName
* JmDNS name
* @return new HostInfo
*/
public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
Log.i("mDNS","newHostInfo");
HostInfo localhost = null;
String aName = "";
InetAddress addr = address;
Log.i("mDNS","addr:"+addr);
try {
if (addr == null) {
String ip = System.getProperty("net.mdns.interface");
Log.i("mDNS","ip"+ip);
if (ip != null) {
addr = InetAddress.getByName(ip);
} else {
addr = InetAddress.getLocalHost();
Log.i("mDNS","addr:"+addr);
if (addr.isLoopbackAddress()) {
// Find local address that isn't a loopback address
InetAddress[] addresses = NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
if (addresses.length > 0) {
addr = addresses[0];
}
}
}
aName = addr.getHostName();
if (addr.isLoopbackAddress()) {
logger.warning("Could not find any address beside the loopback.");
}
} else {
aName = addr.getHostName();
}
if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
}
} catch (final IOException e) {
logger.log(Level.WARNING, "Could not intialize the host network interface on " + address + "because of an error: " + e.getMessage(), e);
// This is only used for running unit test on Debian / Ubuntu
addr = loopbackAddress();
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
}
// A host name with "." is illegal. so strip off everything and append .local.
aName = aName.replace('.', '-');
aName += ".local.";
localhost = new HostInfo(addr, aName, dns);
return localhost;
}
public static PingResult ping(InetAddress host, PingOptions pingOptions) throws IOException, InterruptedException {
PingResult pingResult = new PingResult(host);
if (host == null) {
pingResult.isReachable = false;
return pingResult;
}
StringBuilder echo = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
int timeoutSeconds = Math.max(pingOptions.getTimeoutMillis() / 1000, 1);
int ttl = Math.max(pingOptions.getTimeToLive(), 1);
String address = host.getHostAddress();
String pingCommand = "ping";
if (address != null) {
if (IPTools.isIPv6Address(address)) {
// If we detect this is a ipv6 address, change the to the ping6 binary
pingCommand = "ping6";
} else if (!IPTools.isIPv4Address(address)) {
// Address doesn't look to be ipv4 or ipv6, but we could be mistaken
}
} else {
// Not sure if getHostAddress ever returns null, but if it does, use the hostname as a fallback
address = host.getHostName();
}
Process proc = runtime.exec(pingCommand + " -c 1 -W " + timeoutSeconds + " -t " + ttl + " " + address);
proc.waitFor();
int exit = proc.exitValue();
String pingError;
switch (exit) {
case 0:
InputStreamReader reader = new InputStreamReader(proc.getInputStream());
BufferedReader buffer = new BufferedReader(reader);
String line;
while ((line = buffer.readLine()) != null) {
echo.append(line).append("\n");
}
return getPingStats(pingResult, echo.toString());
case 1:
pingError = "failed, exit = 1";
break;
default:
pingError = "error, exit = 2";
break;
}
pingResult.error = pingError;
proc.destroy();
return pingResult;
}