| 1 | package cz.vutbr.feec.session.common; |
| 2 | |
| 3 | import java.net.InetAddress; |
| 4 | import java.net.NetworkInterface; |
| 5 | import java.net.SocketException; |
| 6 | import java.util.Enumeration; |
| 7 | |
| 8 | /** |
| 9 | * The Class NetUtils. |
| 10 | */ |
| 11 | public class NetUtils { |
| 12 | |
| 13 | /** |
| 14 | * Return ip number of interface. |
| 15 | * |
| 16 | * @param ifNumber number of possition of iface. |
| 17 | * |
| 18 | * @return the local address |
| 19 | */ |
| 20 | public static InetAddress getLocalAddress(int ifNumber) { |
| 21 | try { |
| 22 | Enumeration<NetworkInterface> eNI = NetworkInterface |
| 23 | .getNetworkInterfaces(); |
| 24 | |
| 25 | NetworkInterface cNI; |
| 26 | Enumeration<InetAddress> eIA; |
| 27 | InetAddress cIA = null; |
| 28 | |
| 29 | |
| 30 | |
| 31 | for (; eNI.hasMoreElements();) { |
| 32 | cNI = eNI.nextElement(); |
| 33 | eIA = cNI.getInetAddresses(); |
| 34 | int counter = 1; |
| 35 | for (; eIA.hasMoreElements();) { |
| 36 | cIA = eIA.nextElement(); |
| 37 | if(counter == ifNumber) { |
| 38 | // return cIA.getHostAddress(); |
| 39 | return cIA; |
| 40 | } |
| 41 | counter++; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | return cIA; |
| 46 | } catch (SocketException eS) { |
| 47 | System.out.println("ERROR - SocketException"); |
| 48 | System.out.println("ERROR - " + eS.getLocalizedMessage()); |
| 49 | eS.printStackTrace(); |
| 50 | System.exit(2); |
| 51 | return null; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Gets the local address string. |
| 57 | * |
| 58 | * @param pozition the pozition |
| 59 | * |
| 60 | * @return the local address string |
| 61 | */ |
| 62 | public static String getLocalAddressString(int pozition) { |
| 63 | String str = getLocalAddress(2).toString(); |
| 64 | return str.substring(1, str.length()); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Convert addr. |
| 69 | * |
| 70 | * @param addr the addr |
| 71 | * |
| 72 | * @return the string |
| 73 | */ |
| 74 | public static String convertAddr(byte[] addr) { |
| 75 | return ""+(addr[0]&0xff)+"."+(addr[1]&0xff)+"." |
| 76 | +(addr[2]&0xff)+"."+(addr[3]&0xff); |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Gets the local address byte. |
| 81 | * |
| 82 | * @return the local address byte |
| 83 | */ |
| 84 | public static byte[] getLocalAddressByte() { |
| 85 | return getLocalAddress(2).getAddress(); |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | /** |
| 91 | * The main method. |
| 92 | * |
| 93 | * @param args the args |
| 94 | */ |
| 95 | public static void main(String[] args) { |
| 96 | System.out.println(NetUtils.getLocalAddressString(2)); |
| 97 | byte[] b = NetUtils.getLocalAddressByte(); |
| 98 | System.out.println(NetUtils.convertAddr(b)); |
| 99 | |
| 100 | } |
| 101 | } |