java获取ip和端口号
时间: 2023-10-30 20:07:04 浏览: 175
java获取Ip
在Java中获取IP和端口号的方法有多种,以下是其中两种常用的方式:
1.使用Socket类获取本地IP和端口号:
```java
import java.net.*;
public class GetLocalIpAndPort {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
String ip = inetAddress.getHostAddress();
System.out.println("本机IP地址:" + ip);
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, 0));
int port = socket.getLocalPort();
System.out.println("本机端口号:" + port);
}
}
```
2.使用ServerSocket类获取本地IP和端口号:
```java
import java.net.*;
public class GetLocalIpAndPort {
public static void main(String[] args) throws UnknownHostException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
InetAddress inetAddress = InetAddress.getLocalHost();
String ip = inetAddress.getHostAddress();
System.out.println("本机IP地址:" + ip);
int port = serverSocket.getLocalPort();
System.out.println("本机端口号:" + port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上两种方式都可以获取本机IP和随机端口号,如果需要指定端口号,可以将0替换为需要的端口号。
阅读全文