private final void socketrun() { do { if (link.socketport != 0) { try { Socket socket = new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport); socket.setSoTimeout(30000); socket.setTcpNoDelay(true); link.s = socket; } catch (Exception _ex) { link.s = null; } link.socketport = 0; } if (link.runme != null) { Thread thread = new Thread(link.runme); thread.setDaemon(true); thread.start(); link.runme = null; } if (link.iplookup != null) { String s = "unknown"; try { s = InetAddress.getByName(link.iplookup).getHostName(); } catch (Exception _ex) { } link.host = s; link.iplookup = null; } try { Thread.sleep(100L); } catch (Exception _ex) { } } while (true); }
private String detectAgentUrl( HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) { serverAddress = pServer.getAddress(); InetAddress realAddress; int port; if (serverAddress != null) { realAddress = serverAddress.getAddress(); if (realAddress.isAnyLocalAddress()) { try { realAddress = NetworkUtil.getLocalAddress(); } catch (IOException e) { try { realAddress = InetAddress.getLocalHost(); } catch (UnknownHostException e1) { // Ok, ok. We take the original one realAddress = serverAddress.getAddress(); } } } port = serverAddress.getPort(); } else { realAddress = pConfig.getAddress(); port = pConfig.getPort(); } return String.format( "%s://%s:%d%s", pConfig.getProtocol(), realAddress.getHostAddress(), port, pContextPath); }
/** A helper api to add remote IP address */ static void addRemoteIP(StringBuilder b) { InetAddress ip = Server.getRemoteIp(); // ip address can be null for testcases if (ip != null) { add(Keys.IP, ip.getHostAddress(), b); } }
@Override protected Void doInBackground(Void... params) { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface thisInterface = networkInterfaces.nextElement(); Enumeration<InetAddress> inetAddresses = thisInterface.getInetAddresses(); if (inetAddresses.hasMoreElements()) { String niInfo = thisInterface.getDisplayName() + "\n"; while (inetAddresses.hasMoreElements()) { InetAddress thisAddress = inetAddresses.nextElement(); niInfo += "---\n"; niInfo += "Address: " + thisAddress.getAddress() + "\n"; niInfo += "CanonicalHostName: " + thisAddress.getCanonicalHostName() + "\n"; niInfo += "HostAddress: " + thisAddress.getHostAddress() + "\n"; niInfo += "HostName: " + thisAddress.getHostName() + "\n"; } publishProgress(niInfo); } } } catch (SocketException e) { e.printStackTrace(); } return null; }
/** * Connects this CDDB instance to the CDDB server running on the supplied host using the specified * port. * * <p><b>Note well:</b> you must close a CDDB connection once you are done with it, otherwise the * socket connection will remain open and pointlessly consume machine resources. * * @param hostname The host to which to connect. * @param port The port number on which to connect to the host. * @exception IOException Thrown if a network error occurs attempting to connect to the host. * @exception CDDBException Thrown if an error occurs after identifying ourselves to the host. * @return The message supplied with the succesful connection response. * @see #close */ public String connect(String hostname, int port) throws IOException, CDDBException { // obtain the necessary information we'll need to identify // ourselves to the CDDB server String localhost = InetAddress.getLocalHost().getHostName(); String username = System.getProperty("user.name"); if (username == null) { username = "******"; } // establish our socket connection and IO streams InetAddress addr = InetAddress.getByName(hostname); _sock = new Socket(addr, port); _in = new BufferedReader(new InputStreamReader(_sock.getInputStream())); _out = new PrintStream(new BufferedOutputStream(_sock.getOutputStream())); // first read (and discard) the banner string _in.readLine(); // send a hello request StringBuilder req = new StringBuilder("cddb hello "); req.append(username).append(" "); req.append(localhost).append(" "); req.append(CLIENT_NAME).append(" "); req.append(CLIENT_VERSION); Response rsp = request(req.toString()); // confirm that the response was a successful one if (CDDBProtocol.codeFamily(rsp.code) != CDDBProtocol.OK && rsp.code != 402 /* already shook hands */) { throw new CDDBException(rsp.code, rsp.message); } return rsp.message; }
/** * Special Yahoo connect routines. We resolve hostname IP address and try each one until connected * * @param account * @param store * @return * @throws java.net.UnknownHostException */ private static int yahooConnect( Account account, IMAPStore store, boolean specialYahooConnectEnabled) throws UnknownHostException, MessagingException { int connectionAttempts = 0; store.SetIDCommand( "ID (\"vendor\" \"Zimbra\" \"os\" \"Windows XP\" \"os-version\" \"5.1\" \"guid\" \"4062-5711-9195-4050\")"); if (specialYahooConnectEnabled) { InetAddress[] addresses = InetAddress.getAllByName(account.getReceiveHost()); for (InetAddress address : addresses) { try { store.connect(address.getHostAddress(), account.getLoginName(), account.getPassword()); connectionAttempts++; break; } catch (Throwable t) { } } } else { store.connect(account.getReceiveHost(), account.getLoginName(), account.getPassword()); connectionAttempts++; } return connectionAttempts; }
/** * Add a standardised amount of information about an interface. This is in the form: * * <pre> * [interfaces] * | * | * +--[ id ] (branch) * | | * | +-- "order" (integer metric: 1 .. 2 ..) * | +-- "FQDN" (string metric: the host's FQDN, as presented by the door) * | +-- "address" (string metric: the host's address; e.g., "127.0.0.1") * | +-- "address-type" (string metric: "IPv4", "IPv6" or "unknown") * | +-- "scope" (string metric: "IPv4", "IPv6" or "unknown") * | * </pre> * * @param update The StateUpdate to append the new metrics. * @param parentPath the path that the id branch will be added. * @param lifetime how long the created metrics should last. */ private void addInterfaceInfo( StateUpdate update, StatePath parentPath, InetAddress address, long lifetime) { StatePath pathToInterfaceBranch = parentPath.newChild(address.getHostAddress()); String hostName = address.getHostName(); update.appendUpdate( pathToInterfaceBranch.newChild("FQDN"), new StringStateValue(hostName, lifetime)); String urlName = (isInetAddress(hostName)) ? toUriString(address) : hostName; update.appendUpdate( pathToInterfaceBranch.newChild("url-name"), new StringStateValue(urlName, lifetime)); update.appendUpdate( pathToInterfaceBranch.newChild("address"), new StringStateValue(address.getHostAddress(), lifetime)); update.appendUpdate( pathToInterfaceBranch.newChild("address-type"), new StringStateValue( (address instanceof Inet4Address) ? "IPv4" : (address instanceof Inet6Address) ? "IPv6" : "unknown", lifetime)); update.appendUpdate( pathToInterfaceBranch.newChild("scope"), new StringStateValue(NetworkUtils.InetAddressScope.of(address).toString().toLowerCase())); }
@Override public String toString() { if (isRequest()) return String.format( "Who has %s? Tell %s", targetIp.getHostAddress(), senderIp.getHostAddress()); else return String.format("%s is at %s", senderIp.getHostAddress(), senderMac); }
public static String getIPAddress(boolean useIPv4) throws SocketException { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { if (sAddr.startsWith("fe80") || sAddr.startsWith("FE80")) // skipping link-local addresses continue; int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } return ""; }
@Override public DiscoveryResult createResult(ServiceInfo service) { if (service.getApplication().contains("mieleathome")) { ThingUID uid = getThingUID(service); if (uid != null) { Map<String, Object> properties = new HashMap<>(2); InetAddress[] addresses = service.getInetAddresses(); if (addresses.length > 0 && addresses[0] != null) { properties.put(MieleBindingConstants.HOST, addresses[0].getHostAddress()); Socket socket = null; try { socket = new Socket(addresses[0], 80); InetAddress ourAddress = socket.getLocalAddress(); properties.put(MieleBindingConstants.INTERFACE, ourAddress.getHostAddress()); } catch (IOException e) { logger.error( "An exception occurred while connecting to the Miele Gateway : '{}'", e.getMessage()); } } return DiscoveryResultBuilder.create(uid) .withProperties(properties) .withRepresentationProperty(uid.getId()) .withLabel("Miele XGW3000 Gateway") .build(); } } return null; }
private Core() { boolean f = false; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = (NetworkInterface) en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { String ipAddress = inetAddress.getHostAddress().toString(); this.ip = inetAddress; f = true; break; } } if (f) break; } } catch (SocketException ex) { ex.printStackTrace(); System.exit(1); } this.teams = new HashMap<String, Team>(); this.judges = new HashMap<String, Judge>(); this.problems = new HashMap<String, ProblemInfo>(); this.scheduler = new Scheduler(); this.timer = new ContestTimer(300 * 60); try { readConfigure(); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort); }
private NetworkInterface GetExternalNetworkInterface() { try { // iterate over the network interfaces known to java Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); OUTER: for (NetworkInterface interface_ : Collections.list(interfaces)) { // we shouldn't care about loopback addresses if (interface_.isLoopback()) continue; // if you don't expect the interface to be up you can skip this // though it would question the usability of the rest of the code if (!interface_.isUp()) continue; // iterate over the addresses associated with the interface Enumeration<InetAddress> addresses = interface_.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { // look only for ipv4 addresses if (address instanceof Inet6Address) continue; // use a timeout big enough for your needs if (!address.isReachable(3000)) continue; return interface_; } } } catch (Exception e) { e.printStackTrace(); } return null; }
static void readConfig() { tracker_ip = COConfigurationManager.getStringParameter("Tracker IP", ""); tracker_ip = UrlUtils.expandIPV6Host(tracker_ip); String override_ips = COConfigurationManager.getStringParameter("Override Ip", ""); StringTokenizer tok = new StringTokenizer(override_ips, ";"); Map new_override_map = new HashMap(); while (tok.hasMoreTokens()) { String ip = tok.nextToken().trim(); if (ip.length() > 0) { new_override_map.put(AENetworkClassifier.categoriseAddress(ip), ip); } } override_map = new_override_map; InetAddress bad = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress(); if (bad == null || bad.isAnyLocalAddress()) { bind_ip = ""; } else { bind_ip = bad.getHostAddress(); } }
/** 取得local host的地址,如果有可能,取得物理MAC地址。 */ private static byte[] getLocalHostAddress() { Method getHardwareAddress; try { getHardwareAddress = NetworkInterface.class.getMethod("getHardwareAddress"); } catch (Exception e) { getHardwareAddress = null; } byte[] addr; try { InetAddress localHost = InetAddress.getLocalHost(); if (getHardwareAddress != null) { addr = (byte[]) getHardwareAddress.invoke( NetworkInterface.getByInetAddress(localHost)); // maybe null } else { addr = localHost.getAddress(); } } catch (Exception e) { addr = null; } if (addr == null) { addr = new byte[] {127, 0, 0, 1}; } return addr; }
public MockConnectionInfo(IPv4Addr addr, int port) throws UnknownHostException { super(null, ConnectionType.ACTIVE); this.remoteAddr = InetAddress.getByAddress(addr.toBytes()); this.remotePort = port; this.localAddr = InetAddress.getLocalHost(); this.localPort = new Random().nextInt(1000) + 51000; }
public static String getIPaddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface interf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = interf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ipAddres = inetAddress.getHostAddress().toString(); Log.e("ip address: ", ipAddres); return ipAddres; } } } } catch (SocketException ex) { Log.e("SOCKET EXCEPTION in get IP ADDDRESs", ex.toString()); } return null; }
/** Creates the server. */ public static void main(String args[]) { client = null; ServerSocket server = null; try { System.out.print("\nCreating Server...\n"); // creates the server server = new ServerSocket(8008); System.out.print("Created\n"); // get the ip Address and the host name. InetAddress localAddr = InetAddress.getLocalHost(); System.out.println("IP address: " + localAddr.getHostAddress()); System.out.println("Hostname: " + localAddr.getHostName()); } catch (IOException e) { // sends a System.out.println("IO" + e); } // constantly checks for a new aocket trying to attach itself to the trhead while (true) { try { client = server.accept(); // create a new thread. FinalMultiThread thr = new FinalMultiThread(client); System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n"); CliList.add(thr); current++; thr.start(); } catch (IOException e) { System.out.println(e); } } }
// 获得IP地址 public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; }
private DatagramChannel connectClient() throws IOException { final DatagramChannel client = address.isMulticastAddress() ? DatagramChannel.open(address.getAddress().length == 4 ? INET : INET6) : DatagramChannel.open(); final InetSocketAddress hostAddress = new InetSocketAddress(port); client.configureBlocking(false); if (address.isMulticastAddress()) { client.setOption(SO_REUSEADDR, true); client.bind(hostAddress); if (networkInterface != null) { // This is probably not needed, because client socket doesn't send datagrams, // but since EVERYBODY on the internet configures this for any channels, and // I don't see any harm this config could make, I leave it here client.setOption(IP_MULTICAST_IF, networkInterface); client.join(address, networkInterface); } else { client.join(address, NetworkInterface.getByInetAddress(hostAddress.getAddress())); } if (LOG.isDebugEnabled()) LOG.debug("Connecting via multicast, group=" + address); } else { client.bind(hostAddress); } if (LOG.isDebugEnabled()) LOG.debug("Listening on port " + port); closeables.add(client); return client; }
// ------------------------------------------------------------ private void extractPacketData(StorageServer serv, DatagramPacket receivePacket) throws IOException { try { byte[] temp = new byte[4]; System.arraycopy(receivePacket.getData(), 3, temp, 0, 4); serv.IP = InetAddress.getByAddress(temp).getHostAddress(); // System.out.println("serv.ip: " + serv.IP); // serv.IP = receivePacket.getAddress().getHostAddress(); // System.out.println("serv.ip: " + serv.IP); // System.out.println("inetaddress.getbyname() : " + // InetAddress.getByName(gwIP)) /* * serv.IP = String.valueOf(receivePacket.getData()[3]) + "." + * String.valueOf(receivePacket.getData()[4]) + "." + * String.valueOf(receivePacket.getData()[5]) + "." + * String.valueOf(receivePacket.getData()[6]); */ serv.port = (int) (receivePacket.getData()[7] << 8) + receivePacket.getData()[8]; System.out.println("Connecting to: " + serv.IP + ":" + serv.port); Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port); serv.sock = s; } catch (IOException e) { System.out.println( "BIG PROBLEM HERE BECAUSE YOU CANNOT CONNECT " + "BACK!!!!!!!! Trying other address"); try { serv.IP = receivePacket.getAddress().getHostAddress(); System.out.println("Connecting to: " + serv.IP + ":" + serv.port); Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port); serv.sock = s; } catch (IOException f) { System.out.println("cannot connect here aswell\n"); throw new IOException(f); } } }
/** * Returns if the host is currently reachable. * * <p>If the host is unreachable, this method will not try again for up to 30 seconds. * * @return If the host is reachable. */ public boolean isAvailable() { if (!UpnpDiscoverer.getDevicePingDetection()) return true; // We are not protected from the remote address suddenly changing. InetAddress remoteAddress = this.remoteAddress; if (remoteAddress != null) { if (System.currentTimeMillis() > timeout) { try { boolean returnValue = remoteAddress.isReachable(UpnpDiscoverer.getDevicePingTimeout()); if (returnValue) { return true; } else { logger.warn("Unable to ping the remote address {}.", remoteAddress.toString()); } } catch (Exception e) { logger.error("Unable to ping the remote address {} => ", remoteAddress.toString(), e); } // Set the timeout for 30 seconds from now. This way when multiple capture devices // on one host are unavailable we don't waste time finding out what we already know // for at least 30 more seconds which should be more than enough time to find a // better capture device or come back to this one and try to use it anyway. timeout = System.currentTimeMillis() + 30000; } return false; } return true; }
public boolean isReachable(InetAddress addr, int timeout, NetworkInterface netif, int ttl) throws IOException { byte[] ifaddr = null; int scope = -1; int netif_scope = -1; if (netif != null) { /* * Let's make sure we bind to an address of the proper family. * Which means same family as addr because at this point it could * be either an IPv6 address or an IPv4 address (case of a dual * stack system). */ java.util.Enumeration<InetAddress> it = netif.getInetAddresses(); InetAddress inetaddr = null; while (it.hasMoreElements()) { inetaddr = it.nextElement(); if (inetaddr.getClass().isInstance(addr)) { ifaddr = inetaddr.getAddress(); if (inetaddr instanceof Inet6Address) { netif_scope = ((Inet6Address) inetaddr).getScopeId(); } break; } } if (ifaddr == null) { // Interface doesn't support the address family of // the destination return false; } } if (addr instanceof Inet6Address) scope = ((Inet6Address) addr).getScopeId(); return isReachable0(addr.getAddress(), scope, timeout, ifaddr, ttl, netif_scope); }
private void findMachinesBasedOnLocalIp() { Optional<InetAddress> localhost = getLocalAddress(); if (localhost.isPresent()) { InetAddress inetAddress = localhost.get(); myIp = inetAddress.getAddress(); scanningThreadPool.submit( new Runnable() { @Override public void run() { if (!isCancelled()) { searchForIp(myIp); } } }); for (int i = 1; i <= MAX_IPS; i++) { final int finalI = i; scanningThreadPool.submit( new Runnable() { @Override public void run() { if (!isCancelled()) { searchForIp(createSubnetAddress(myIp, (byte) finalI)); } } }); } } }
public RConQueryThread(IServer par1IServer) { queryPort = ModuleSnooper.port; serverHostname = ModuleSnooper.hostname; serverPort = par1IServer.getPort(); queryHostname = "0.0.0.0"; server = par1IServer; if (0 != serverHostname.length() && !queryHostname.equals(serverHostname)) { queryHostname = serverHostname; } else { serverHostname = "0.0.0.0"; try { InetAddress var2 = InetAddress.getLocalHost(); queryHostname = var2.getHostAddress(); } catch (UnknownHostException var3) { logWarning( "Unable to determine local host IP, please set server-ip/hostname in the snooper config : " + var3.getMessage()); } } if (0 == queryPort) { queryPort = serverPort; logInfo("Setting default query port to " + queryPort); } field_72644_p = new HashMap(); queryClients = new HashMap(); time = (new Date()).getTime(); }
/** * Get IP address from first non-localhost interface * * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port // suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; }
public static boolean validateProxy(HttpHost p) { if (localAddr == null) { logger.error("cannot get local IP"); return false; } boolean isReachable = false; Socket socket = null; try { socket = new Socket(); socket.bind(new InetSocketAddress(localAddr, 0)); InetSocketAddress endpointSocketAddr = new InetSocketAddress(p.getAddress().getHostAddress(), p.getPort()); socket.connect(endpointSocketAddr, 3000); logger.debug( "SUCCESS - connection established! Local: " + localAddr.getHostAddress() + " remote: " + p); isReachable = true; } catch (IOException e) { logger.warn( "FAILRE - CAN not connect! Local: " + localAddr.getHostAddress() + " remote: " + p); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { logger.warn("Error occurred while closing socket of validating proxy", e); } } } return isReachable; }
private void setupProxy( ConnectivitySettings cs, int connectionType, InetSocketAddress inetSocketAddress) { cs.setConnectionType(connectionType); InetAddress address = inetSocketAddress.getAddress(); cs.setProxyHost((address != null) ? address.getHostAddress() : inetSocketAddress.getHostName()); cs.setProxyPort(inetSocketAddress.getPort()); }
/** * 根据网卡取本机配置的内网IP 如果是双网卡的,则取出内网IP * * @return String 内网IP地址 */ public static String getLocalIp() { String localip = null; // 本地IP,如果没有配置外网IP则返回它 try { 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().indexOf(":") == -1) { localip = ip.getHostAddress(); finded = true; break; } } } } catch (SocketException e) { logger.error(e); } return localip; }
/** * The name for this host. * * @see #HOSTNAME * @see <a href="http://trac.bigdata.com/ticket/886" >Provide workaround for bad reverse DNS * setups</a> */ public static final String getCanonicalHostName() { String s = System.getProperty(HOSTNAME); if (s != null) { // Trim whitespace. s = s.trim(); } if (s != null && s.length() != 0) { log.warn("Hostname override: hostname=" + s); } else { try { /* * Note: This should be the host *name* NOT an IP address of a * preferred Ethernet adaptor. */ s = InetAddress.getLocalHost().getCanonicalHostName(); } catch (Throwable t) { log.warn("Could not resolve canonical name for host: " + t); } try { s = InetAddress.getLocalHost().getHostName(); } catch (Throwable t) { log.warn("Could not resolve name for host: " + t); s = "localhost"; } } return s; }
/** * 取得本机IP地址 (多网卡主机返回其中一张网卡的IP) * * @param isInter 是否返回内网IP(默认网段为19.2.) * @return 本机ip地址 */ public static synchronized String getLocalIP(boolean isInter) { // 初始化本地地址列表 if (localAddressList == null) { localAddressList = getLocalAddresses(); } String localIP = ""; for (InetAddress ia : localAddressList) { String ip = ia.getHostAddress(); // 忽略ipv6地址和loopback地址 if (ia instanceof Inet6Address || ip.startsWith("127")) { continue; } // 记录找到的第一个ipv4地址 if (StringUtil.isNullOrBlank(localIP)) { localIP = ip; } if (isInter && ip.startsWith("19.")) { return ip; } if (!isInter && !ip.startsWith("19.")) { return ip; } } return localIP; }