Socket:一台機器的通訊節點稱為socket,在java中,socket是java.net包裡面的Socket,ServerSocket,DataGramSocket,MultiSocket的實例。
IP地址java中用java.net.InetAddress來表示。
java network address class包括:
InetAddress:ip地址或者域名,指向遠程地址。如果域名解析不了,則出錯。
抽象類,有兩個子類:Inet4Address和Inet6Address。這兩個類智能通過InetAddress的靜態方法獲取,不能直接構造。包可見。
InetSocketAddress extends SocketAddress:ip socket地址,用{ip,port}或者{hostname,port}表示。也能夠單獨用port構造,表示本機ip地址,所有本機網絡地址。
NetwordInterface:本機網絡接口,由多個網絡接口名稱和對應的網絡接口的ip地址列表構成。
網絡主機有兩個特殊的網絡地址:
loopback:127.0.0.1 用來檢測本機的host名稱,或者檢測本地ip地址是否可用
wildcard:0.0.0.0 綁定了本機所有的ip地址
- import java.io.IOException;
- import java.net.Inet4Address;
- import java.net.InterfaceAddress;
- import java.net.NetworkInterface;
- import java.util.Enumeration;
-
-
- public class LocalIP {
-
- private static final void printIp() {
-
- try {
- for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
- NetworkInterface item = e.nextElement();
-
- System.out.println(item.toString());
- System.out.println(item.getMTU() + " " + item.isLoopback() + " " + item.isPointToPoint() + " " + item.isUp() + " " + item.isVirtual());
-
- for (InterfaceAddress address : item.getInterfaceAddresses()) {
- if (address.getAddress() instanceof Inet4Address) {
- Inet4Address inet4Address = (Inet4Address) address.getAddress();
- System.out.println(inet4Address.getHostAddress());
- System.out.println(inet4Address.isLinkLocalAddress() + " " + inet4Address.isLoopbackAddress() + " " + inet4Address.isMCGlobal() + " " + inet4Address.isMulticastAddress());
- }
- }
- }
- } catch (IOException ex) {
-
- }
- }
- public static void main(String[] args) {
- printIp();
- }
- }