|
| 1 | +package com.baeldung.iplookup; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.net.DatagramSocket; |
| 7 | +import java.net.InetAddress; |
| 8 | +import java.net.InetSocketAddress; |
| 9 | +import java.net.Socket; |
| 10 | +import java.net.SocketException; |
| 11 | +import java.net.URL; |
| 12 | +import java.net.UnknownHostException; |
| 13 | + |
| 14 | +public class IPAddressLookup { |
| 15 | + public static void main(String[] args) { |
| 16 | + System.out.println("UDP connection IP lookup: " + getLocalIpAddressUdp()); |
| 17 | + System.out.println("Socket connection IP lookup: " + getLocalIpAddressSocket()); |
| 18 | + System.out.println("AWS connection IP lookup: " + getPublicIpAddressAws()); |
| 19 | + } |
| 20 | + |
| 21 | + public static String getLocalIpAddressUdp() { |
| 22 | + try (final DatagramSocket datagramSocket = new DatagramSocket()) { |
| 23 | + datagramSocket.connect(InetAddress.getByName("8.8.8.8"), 12345); |
| 24 | + return datagramSocket.getLocalAddress().getHostAddress(); |
| 25 | + } catch (SocketException | UnknownHostException exception) { |
| 26 | + throw new RuntimeException(exception); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public static String getLocalIpAddressSocket() { |
| 31 | + try (Socket socket = new Socket()) { |
| 32 | + socket.connect(new InetSocketAddress("google.com", 80)); |
| 33 | + return socket.getLocalAddress().getHostAddress(); |
| 34 | + } catch (IOException e) { |
| 35 | + throw new RuntimeException(e); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public static String getPublicIpAddressAws() { |
| 40 | + try { |
| 41 | + String urlString = "http://checkip.amazonaws.com/"; |
| 42 | + URL url = new URL(urlString); |
| 43 | + try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) { |
| 44 | + return br.readLine(); |
| 45 | + } |
| 46 | + } catch (IOException e) { |
| 47 | + throw new RuntimeException(e); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments