← 返回首页
JavaSE系列教程(一百零一)
发表时间:2021-12-14 09:49:24
网络编程基础

计算机网络是指两台或更多的计算机组成的网络,在同一个网络中,任意两台计算机都可以直接通信,因为所有计算机都需要遵循同一种网络协议。

1.网络模型

计算机网络模型,必须采用分层模型,每一层负责处理自己的操作。OSI(Open System Interconnect)网络模型是ISO组织定义的一个计算机互联的标准模型,但是这个模型仅仅是一个标准没有具体实现。而TCP/IP模型是OSI七层模型的具体实现。

2.IP地址

在互联网中一个计算机会对应一个或者多个IP地址,IP地址就是计算机在互联网中的标识符。

IP地址分为IPv4和IPv6两种。IPv4采用32位地址,类似101.202.99.12,而IPv6采用128位地址,类似2001:0DA8:100A:0000:0000:1020:F2F3:1428。IPv4地址总共有232个(大约42亿),而IPv6地址则总共有2128个(大约340万亿亿亿亿),IPv4的地址目前已耗尽,而IPv6的地址是个宇宙级的超大数量,毫不夸张的讲地球上的每一粒沙子分配一个IPv6地址也用不完。

3.获取IP地址

java.net 包里包含了常用的网络操作的API和接口。

实例: 获取IPV4和IPV6地址。

import java.net.*;
import java.util.Enumeration;

/*
 * Java获得IP地址
 *
 * */
public class IpAddressDemo {

    public static String getLocalIPv6Address() throws SocketException {
        InetAddress inetAddress = null;

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        outer: //退出多重循环
        while (networkInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> inetAds = networkInterfaces.nextElement().getInetAddresses();
            while (inetAds.hasMoreElements()) {
                inetAddress = inetAds.nextElement();
                //检查此地址是否是IPv6地址以及是否是保留地址
                if (inetAddress instanceof Inet6Address && !isReservedAddr(inetAddress)) {
                    break outer;
                }
            }
        }
        String ipAddr = inetAddress.getHostAddress();
        //过滤网卡
        int index = ipAddr.indexOf('%');
        if (index > 0) {
            ipAddr = ipAddr.substring(0, index);
        }

        return ipAddr;
    }
    //判断是否是保留地址
    private static boolean isReservedAddr(InetAddress inetAddr) {
        if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress() || inetAddr.isLoopbackAddress()) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        try {
            InetAddress ipv4_1 = InetAddress.getByName("localhost");
            InetAddress ipv4_2 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1}); //127.0.0.1
            InetAddress ipv4_3 = Inet4Address.getByAddress("localhost", new byte[]{127, 0, 0, 1});
            System.out.println(ipv4_1);
            System.out.println(ipv4_2);
            System.out.println(ipv4_3);

            //获取本机的ipv6的地址。
            System.out.println(getLocalIPv6Address());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

运行结果:

localhost/127.0.0.1
/127.0.0.1
localhost/127.0.0.1
fe80:0:0:0:10b5:1ab9:f65:4351