Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.net.*;

import java.util.*;

public class Main {
    public static void checkIfValidAddress(InetAddress bind_addr, String prot_name) throws Exception {
        //if(bind_addr.isAnyLocalAddress() || bind_addr.isLoopbackAddress())
        //  return;
        Collection<InetAddress> addrs = getAllAvailableAddresses();
        for (InetAddress addr : addrs) {
            if (addr.equals(bind_addr))
                return;
        }
        throw new BindException(
                "[" + prot_name + "] " + bind_addr + " is not a valid address on any local network interface");
    }

    public static Collection<InetAddress> getAllAvailableAddresses() {
        Set<InetAddress> retval = new HashSet<InetAddress>();
        Enumeration en;

        try {
            en = NetworkInterface.getNetworkInterfaces();
            if (en == null)
                return retval;
            while (en.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                Enumeration<InetAddress> addrs = intf.getInetAddresses();
                while (addrs.hasMoreElements())
                    retval.add(addrs.nextElement());
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return retval;
    }
}