summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/taskmanager/tasks/LocalAddressesList.java
blob: ad5d5399881f036e834f5e7c6fabd3ab9bee9f04 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package org.openslx.taskmanager.tasks;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.log4j.Logger;
import org.openslx.taskmanager.api.AbstractTask;

public class LocalAddressesList extends AbstractTask
{
	private static final Logger LOG = Logger.getLogger( LocalAddressesList.class );

	private Output status = new Output();

	@Override
	protected boolean initTask()
	{
		return true;
	}

	@Override
	protected boolean execute()
	{
		this.setStatusObject( status );
		List<Output.Entry> list = new ArrayList<>();
		try {
			for ( Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
				NetworkInterface intf = en.nextElement();
				for ( Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
					InetAddress addr = enumIpAddr.nextElement();
					Output.Entry entry = new Output.Entry();
					entry.iface = intf.getName();
					entry.ip = addr.getHostAddress().replaceFirst( "%\\d+$", "" );
					if ( addr instanceof Inet4Address ) {
						entry.type = "ipv4";
					} else if ( addr instanceof Inet6Address ) {
						entry.type = "ipv6";
					} else {
						entry.type = addr.getClass().getSimpleName();
					}
					list.add( entry );
				}
			}
		} catch ( SocketException e ) {
			LOG.info( " (error retrieving network interface list)" );
			this.status.error = "Error retrieving network interface list (" + e.getMessage() + ")";
			return false;
		}
		this.status.addresses = list;
		return true;
	}

	/**
	 * Output - contains additional status data of this task
	 */
	@SuppressWarnings( "unused" )
	private static class Output
	{
		protected String error = null;
		protected List<Entry> addresses = null;

		protected static class Entry
		{
			protected String ip = null;
			protected String iface = null;
			protected String type = null;
		}
	}

}