动态获取服务器ip和端口号工具类

动态获取服务器ip和端口号工具类

package com.jinruan.common.core.utils;

import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpUtil {
   
    private static final Logger logger = LoggerFactory.getLogger( IpUtil.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FTP服务器发送PORT命令时可以使用以下工具类: ```java import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; public class PortCommandUtil { public static void main(String[] args) { try { String ipAddress = "192.168.0.1"; // FTP服务器IP地址 int portRangeStart = 20000; // 起始端口号 int portRangeEnd = 30000; // 结束端口号 String portCommand = generatePortCommand(ipAddress, portRangeStart, portRangeEnd); // 将生成的PORT命令发送给FTP服务器 // 处理FTP服务器的响应 // ... } catch (IOException e) { e.printStackTrace(); } } public static String generatePortCommand(String ipAddress, int portRangeStart, int portRangeEnd) throws IOException { // 获取本机的IP地址 InetAddress localAddress = InetAddress.getLocalHost(); String localIpAddress = localAddress.getHostAddress(); // 在指定的端口范围内查找一个可用的端口号 int availablePort = findAvailablePort(portRangeStart, portRangeEnd); // 将IP地址和端口号转换为PORT命令格式 String[] ipAddressParts = localIpAddress.split("\\."); int[] portParts = { availablePort / 256, availablePort % 256 }; // 构造PORT命令字符串 String portCommand = "PORT " + ipAddressParts[0] + "," + ipAddressParts[1] + "," + ipAddressParts[2] + "," + ipAddressParts[3] + "," + portParts[0] + "," + portParts[1]; return portCommand; } public static int findAvailablePort(int start, int end) throws IOException { for (int port = start; port <= end; port++) { try (ServerSocket serverSocket = new ServerSocket(port)) { // 若端口号未被占用,则返回该端口号 return port; } catch (IOException e) { // 端口号已被占用,继续查找下一个端口号 } } throw new IOException("No available ports in the specified range"); } } ``` 上述代码中,`generatePortCommand`方法用于生成FTP服务器的PORT命令,其中`ipAddress`参数为FTP服务器IP地址,`portRangeStart`和`portRangeEnd`参数为端口号范围。内部使用`findAvailablePort`方法查找可用的端口号,并将本机IP地址和端口号转换为PORT命令格式。最后,`main`方法实现了一个简单的使用示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值