2012/02/15

Java 取得IPv4位址

筆記筆記

import java.io.*;
import java.net.*;
import java.util.*;

public class get {
    public static void main(String[] args) throws IOException {
        ArrayList<String> arrayList = new ArrayList<String>();
        /* 創立一個字串清單 */
        try {
            Enumeration<NetworkInterface> nets = NetworkInterface
                    .getNetworkInterfaces();
            /* 創建一個網路介面的列舉並取得所有介面 */
            for (NetworkInterface n : Collections.list(nets)) {
                Enumeration<InetAddress> ip = n.getInetAddresses();
                /* 創立一個列舉並將取得的IP放進來 */
                for (InetAddress i : Collections.list(ip)) {
                    if (i instanceof Inet4Address
                            && NetworkInterface.getByInetAddress(i).isUp()
                            && !(i.getHostAddress().equals("127.0.0.1"))) {
                        arrayList.add(n.getName().toString());
                        arrayList.add(i.getHostAddress().toString());
                        /*
                         * 清單裡為IPV4的型態,且是網路介面的配置,以及不為127.0.0.1的話加入清單
                         */
                    }
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        }

        // 將檔案指向MyIP.txt
        BufferedWriter fw = new BufferedWriter(new FileWriter("MyIP.txt"));
        for (int i = 0; i < arrayList.size(); i += 2) {
            fw.write("Dev name:" + arrayList.get(i) + "\tIP:"
                    + arrayList.get(i + 1));
            fw.newLine();
        }
        fw.flush();
        fw.close();

    }
}