android: Added NetworkManager class which allows to retrieve a local IP address
[strongswan.git] / src / frontends / android / src / org / strongswan / android / logic / NetworkManager.java
1 /*
2 * Copyright (C) 2012 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 package org.strongswan.android.logic;
17
18 import java.net.Inet4Address;
19 import java.net.Inet6Address;
20 import java.net.InetAddress;
21 import java.net.NetworkInterface;
22 import java.net.SocketException;
23 import java.util.Enumeration;
24
25 public class NetworkManager
26 {
27 public NetworkManager()
28 {
29 }
30
31 /**
32 * Function that retrieves a local address of the given family.
33 *
34 * @param ipv4 true to return an IPv4 address, false for IPv6
35 * @return string representation of an IPv4 address, or null if none found
36 */
37 public String getLocalAddress(boolean ipv4)
38 {
39 try
40 {
41 Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
42 if (en == null)
43 { /* no interfaces at all */
44 return null;
45 }
46 while (en.hasMoreElements())
47 {
48 NetworkInterface intf = en.nextElement();
49 if (intf.isLoopback() || !intf.isUp() ||
50 intf.getName().startsWith("tun"))
51 {
52 continue;
53 }
54 Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
55 while (enumIpAddr.hasMoreElements())
56 {
57 InetAddress inetAddress = enumIpAddr.nextElement();
58 if (inetAddress.isLoopbackAddress())
59 {
60 continue;
61 }
62 if ((ipv4 && inetAddress instanceof Inet4Address) ||
63 (!ipv4 && inetAddress instanceof Inet6Address))
64 {
65 return inetAddress.getHostAddress();
66 }
67 }
68 }
69 }
70 catch (SocketException ex)
71 {
72 ex.printStackTrace();
73 return null;
74 }
75 return null;
76 }
77 }