Java获取服务器IP和端口号

在Java中,我们经常需要获取服务器的IP地址和端口号。这在网络编程中非常常见,特别是在客户端与服务器通信的过程中。本文将介绍如何使用Java编程语言获取服务器的IP地址和端口号,并提供相应的代码示例。

获取服务器IP地址

Java提供了多种方法来获取服务器的IP地址。下面是两种常用的方法:

方法一:使用InetAddress

InetAddress类是Java中用于表示IP地址的类,它提供了获取本地和远程IP地址的方法。使用getLocalHost()方法可以获取本地IP地址,使用getByName(String hostname)方法可以通过主机名或IP地址字符串获取远程IP地址。

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIPAddressExample {

    public static void main(String[] args) {
        try {
            // 获取本地IP地址
            InetAddress localhost = InetAddress.getLocalHost();
            System.out.println("本地IP地址: " + localhost.getHostAddress());

            // 获取远程IP地址
            InetAddress remoteHost = InetAddress.getByName("www.example.com");
            System.out.println("远程IP地址: " + remoteHost.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

方法二:使用NetworkInterface

NetworkInterface类是Java中用于表示网络接口的类,它可以用于获取本地IP地址。使用getNetworkInterfaces()方法可以获取所有可用的网络接口,然后通过遍历接口列表获取每个接口的IP地址。

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

public class GetIPAddressExample {

    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        System.out.println("本地IP地址: " + inetAddress.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

获取服务器端口号

获取服务器端口号的方法相对简单。我们可以通过Java的ServerSocket类获取已绑定到特定端口的服务器套接字的端口号。

import java.io.IOException;
import java.net.ServerSocket;

public class GetPortNumberExample {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            int portNumber = serverSocket.getLocalPort();
            System.out.println("服务器端口号: " + portNumber);
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结

本文介绍了如何使用Java编程语言获取服务器的IP地址和端口号。我们可以使用InetAddress类或NetworkInterface类获取服务器的IP地址,使用ServerSocket类获取服务器的端口号。通过这些方法,我们可以轻松地在Java中获取服务器的IP地址和端口号,以便进行网络编程。

希望本文对您有所帮助!如有任何问题,请随时提问。