Java получить ip адрес компьютера

Java получить ip адрес компьютера

This class represents an Internet Protocol (IP) address. An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. The IP address architecture is defined by RFC 790: Assigned Numbers, RFC 1918: Address Allocation for Private Internets, RFC 2365: Administratively Scoped IP Multicast, and RFC 2373: IP Version 6 Addressing Architecture. An instance of an InetAddress consists of an IP address and possibly its corresponding host name (depending on whether it is constructed with a host name or whether it has already done reverse host name resolution).

Address types

unicast An identifier for a single interface. A packet sent to a unicast address is delivered to the interface identified by that address. The Unspecified Address — Also called anylocal or wildcard address. It must never be assigned to any node. It indicates the absence of an address. One example of its use is as the target of bind, which allows a server to accept a client connection on any interface, in case the server host has multiple interfaces. The unspecified address must not be used as the destination address of an IP packet. The Loopback Addresses — This is the address assigned to the loopback interface. Anything sent to this IP address loops around and becomes IP input on the local host. This address is often used when testing a client.
multicast An identifier for a set of interfaces (typically belonging to different nodes). A packet sent to a multicast address is delivered to all interfaces identified by that address.

IP address scope

Link-local addresses are designed to be used for addressing on a single link for purposes such as auto-address configuration, neighbor discovery, or when no routers are present. Site-local addresses are designed to be used for addressing inside of a site without the need for a global prefix. Global addresses are unique across the internet.

Textual representation of IP addresses

Host Name Resolution

Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned. Reverse name resolution means that for any IP address, the host associated with the IP address is returned. The InetAddress class provides methods to resolve host names to their IP addresses and vice versa.

Читайте также:  Css image src data image

InetAddress Caching

The InetAddress class has a cache to store successful as well as unsuccessful host name resolutions. By default, when a security manager is installed, in order to protect against DNS spoofing attacks, the result of positive host name resolutions are cached forever. When a security manager is not installed, the default behavior is to cache entries for a finite (implementation dependent) period of time. The result of unsuccessful host name resolution is cached for a very short period of time (10 seconds) to improve performance. If the default behavior is not desired, then a Java security property can be set to a different Time-to-live (TTL) value for positive caching. Likewise, a system admin can configure a different negative caching TTL value when needed. Two Java security properties control the TTL values used for positive and negative host name resolution caching:

networkaddress.cache.ttl Indicates the caching policy for successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the successful lookup. The default setting is to cache for an implementation specific period of time. A value of -1 indicates «cache forever». networkaddress.cache.negative.ttl (default: 10) Indicates the caching policy for un-successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups. A value of 0 indicates «never cache». A value of -1 indicates «cache forever».

Method Summary

Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.

Источник

Java получить ip адрес компьютера

This class represents an Internet Protocol (IP) address. An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. The IP address architecture is defined by RFC 790: Assigned Numbers, RFC 1918: Address Allocation for Private Internets, RFC 2365: Administratively Scoped IP Multicast, and RFC 2373: IP Version 6 Addressing Architecture. An instance of an InetAddress consists of an IP address and possibly its corresponding host name (depending on whether it is constructed with a host name or whether it has already done reverse host name resolution).

Address types

Description of unicast and multicast address types
Address Type Description
unicast An identifier for a single interface. A packet sent to a unicast address is delivered to the interface identified by that address. The Unspecified Address — Also called anylocal or wildcard address. It must never be assigned to any node. It indicates the absence of an address. One example of its use is as the target of bind, which allows a server to accept a client connection on any interface, in case the server host has multiple interfaces. The unspecified address must not be used as the destination address of an IP packet. The Loopback Addresses — This is the address assigned to the loopback interface. Anything sent to this IP address loops around and becomes IP input on the local host. This address is often used when testing a client.
multicast An identifier for a set of interfaces (typically belonging to different nodes). A packet sent to a multicast address is delivered to all interfaces identified by that address.
Читайте также:  Netbeans cannot find java

IP address scope

Link-local addresses are designed to be used for addressing on a single link for purposes such as auto-address configuration, neighbor discovery, or when no routers are present. Site-local addresses are designed to be used for addressing inside of a site without the need for a global prefix. Global addresses are unique across the internet.

Textual representation of IP addresses

The textual representation of an IP address is address family specific. For IPv4 address format, please refer to Inet4Address#format; For IPv6 address format, please refer to Inet6Address#format. There is a couple of System Properties affecting how IPv4 and IPv6 addresses are used.

Host Name Resolution

Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned. Reverse name resolution means that for any IP address, the host associated with the IP address is returned. The InetAddress class provides methods to resolve host names to their IP addresses and vice versa.

InetAddress Caching

The InetAddress class has a cache to store successful as well as unsuccessful host name resolutions. By default, when a security manager is installed, in order to protect against DNS spoofing attacks, the result of positive host name resolutions are cached forever. When a security manager is not installed, the default behavior is to cache entries for a finite (implementation dependent) period of time. The result of unsuccessful host name resolution is cached for a very short period of time (10 seconds) to improve performance. If the default behavior is not desired, then a Java security property can be set to a different Time-to-live (TTL) value for positive caching. Likewise, a system admin can configure a different negative caching TTL value when needed. Two Java security properties control the TTL values used for positive and negative host name resolution caching: networkaddress.cache.ttl Indicates the caching policy for successful name lookups from the name service. The value is specified as an integer to indicate the number of seconds to cache the successful lookup. The default setting is to cache for an implementation specific period of time. A value of -1 indicates «cache forever». networkaddress.cache.negative.ttl (default: 10) Indicates the caching policy for un-successful name lookups from the name service. The value is specified as an integer to indicate the number of seconds to cache the failure for un-successful lookups. A value of 0 indicates «never cache». A value of -1 indicates «cache forever».

Method Summary

Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.

Читайте также:  Input type radio css styling

Источник

Получить IP-адрес текущей машины с помощью Java

IP-адрес или адрес интернет-протокола однозначно идентифицирует устройство в Интернете. Поэтому знание идентификатора устройства, на котором запущено наше приложение, является ключевой частью некоторых приложений.

В этом руководстве мы рассмотрим различные методы получения IP-адреса нашего компьютера с помощью Java.

2. Найдите локальный IP-адрес​

Во-первых, давайте рассмотрим некоторые методы получения локального IPv4-адреса текущей машины.

2.1. Локальный адрес с Java Net Library​

Этот метод использует библиотеку Java Net для создания UDP-соединения:

 try (final DatagramSocket datagramSocket = new DatagramSocket())    datagramSocket.connect(InetAddress.getByName("8.8.8.8"), 12345);   return datagramSocket.getLocalAddress().getHostAddress();   > 

Здесь для простоты мы используем первичный DNS Google в качестве целевого хоста и указываем IP-адрес 8.8.8.8. Сетевая библиотека Java в этот момент проверяет только правильность формата адреса, поэтому сам адрес может быть недоступен. Более того, мы используем случайный порт 12345 для создания UDP-соединения с помощью метода socket.connect() . Под капотом он устанавливает все переменные, необходимые для отправки и получения данных, включая локальный адрес машины, фактически не отправляя никаких запросов хосту назначения.

Хотя это решение очень хорошо работает на компьютерах с Linux и Windows, оно вызывает проблемы в macOS и не возвращает ожидаемый IP-адрес.

2.2. Локальный адрес с подключением к сокету​

В качестве альтернативы мы можем использовать сокетное соединение через надежное интернет-соединение для поиска IP-адреса :

 try (Socket socket = new Socket())    socket.connect(new InetSocketAddress("google.com", 80));   return socket.getLocalAddress().getHostAddress();   > 

Здесь, опять же для простоты, мы использовали google.com с подключением к порту 80 , чтобы получить адрес хоста. Мы можем использовать любой другой URL-адрес для создания подключения к сокету, если он доступен.

2.3. Предостережения относительно сложных сетевых ситуаций​

Перечисленные выше методы очень хорошо работают в случае простых сетевых ситуаций. Однако в случаях, когда машина имеет больше сетевых интерфейсов, поведение может быть не таким предсказуемым.

Другими словами, IP-адрес, возвращенный описанными выше функциями, будет адресом предпочтительного сетевого интерфейса на машине. Следовательно, он может отличаться от того, который мы ожидаем. Для конкретных нужд мы можем найти IP-адрес клиента, подключенного к серверу .

3. Найдите общедоступный IP-адрес​

Подобно локальному IP-адресу, нам может понадобиться узнать общедоступный IP-адрес текущей машины. Общедоступный IP-адрес — это адрес IPv4, доступный из Интернета. Более того, он может не однозначно идентифицировать машину, ищущую адрес. Например, несколько хостов под одним и тем же маршрутизатором имеют один и тот же общедоступный IP-адрес.

Просто мы можем подключиться к URL-адресу Amazon AWS checkip.amazonaws.com и прочитать ответ:

 String urlString = "http://checkip.amazonaws.com/";   URL url = new URL(urlString);   try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())))    return br.readLine();   > 

Это хорошо работает большую часть времени. Однако мы явно зависим от внешнего источника, надежность которого не может быть гарантирована. Поэтому в качестве запасного варианта мы можем использовать любой из этих URL-адресов для получения общедоступного IP-адреса :

4. Вывод​

В этой статье мы узнали, как найти IP-адреса текущей машины и как получить их с помощью Java. Мы также рассмотрели различные методы проверки как локальных, так и общедоступных IP-адресов.

И, как всегда, исходный код примеров доступен на GitHub .

Источник

Оцените статью