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

Выезд tpl. Из обзора:

Tpl является библиотекой для сериализации C данные. Данные хранятся в его естественной двоичной форме. API является маленьким и пытается остаться "вне пути". По сравнению с использованием XML tpl быстрее и легче использовать в программах C. Tpl может сериализировать много типов данных C, включая структуры.

9
задан Cœur 16 April 2017 в 07:07
поделиться

2 ответа

In bottom of getHostName() C function gethostbyname(). They initially looking to /etc/hosts, then try resolve through DNS. So, if you add 10.10.11.51 myhostname to /etc/hosts getHostName() should detect it correctly In windows there is analogue to /etc/hosts, AFAIR in \WINDOWS\System32\Servises or so...

This is ONLY name resolution problem.

In your code you first get host name (hostName = InetAddress.getLocalHost().getHostName();) this function return your computer name setted when installing system was installed. Then you get all IP of concrete host name (InetAddress.getAllByName(hostName)) - this return all IP resolved for this hostname

Simple example

1 /etc/hosts like this

127.0.0.1   localhost
127.0.1.1   fred-desktop

your code return

HostName = fred-desktop
HostAddressLocal = 127.0.1.1
hostAddress = 127.0.1.1

2 change /etc/hosts to look like

127.0.0.1   localhost
127.0.1.1   fred-desktop
192.168.1.1 fred-desktop
20.20.20.20 fred-desktop

your code will return

HostName = fred-desktop
HostAddressLocal = 127.0.1.1
hostAddress = 127.0.1.1
hostAddress = 192.168.1.1
hostAddress = 20.20.20.20

fred-desktop - name of my ubuntu box.

-1
ответ дан 4 December 2019 в 21:10
поделиться

As you've already discovered, a computer may very well have several network interfaces with different IP addresses and it's a little bit difficult to guess which one you consider to be "correct", as they are all actually correct.

My crystal ball suggest me that you mean the IP address, which the client is using to connect to the server, from which the applet was loaded. If so, you have at least two possibilities:

  • On the server, you can embed the applet on a dynamically generated HTML page and add the client's IP address as an applet parameter. At least if you're not doing HTTP over a proxy, the web server should be able to determine the client's IP address and pass it on to the applet.

  • In the applet, you can open a TCP socket to the web server from which you loaded the applet and check which local address is being used for the connection:

.

Socket s = new Socket("www", 80);
InetAddress ip = s.getLocalAddress();
s.close();
11
ответ дан 4 December 2019 в 21:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: