1. 程式人生 > >獲取ip地址

獲取ip地址

all name class cat exce eth gethost run string

根據java面向對象的原理,ip地址也被封裝成了對象,InetAdress

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import org.junit.Test;

/**
 * 獲取ip地址
 * @author WangShuang
 *
 */
public class Demo {

    @Test
    public void run1() {
        try {
            //獲取本機的ip地址
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);

            //已知別人的域名 獲取別人的ip地址對象
            InetAddress byName = InetAddress.getByName("www.baidu.com");
            System.out.println(byName);
            String hostAddress = byName.getHostAddress();//返回ip地址的字符串表現形式
            System.out.println(hostAddress);

            InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");
            System.out.println(Arrays.toString(allByName));

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

獲取ip地址