---
title: "(转)重写common-net-ftp以适应内网Passive模式"
author: "0dragon"
date: "2012-06-27T10:19:20Z"
tags: ["common-net", "ftp", "passive", "pasv", "内网"]
categories: ["开源软件"]
slug: "common-net-ftp-passive"
draft: false
lastmod: "2012-06-27T10:19:20Z"
id: 1568766
url: "https://0dragon.iteye.com/blog/1568766"
---

转自\[url]http://www.diybl.com/course/3\_program/java/javajs/20100719/453294.html\[/url] 小心弹出窗口Ad 需要重写几个地方 i. org.apache.commons.net.SocketClient \[code="java"] /\** 用来自定义 Passive 模式的 Host \*/ protected String \_set\_passive\_host = "127.0.0.1"; \[/code] \[code="java"] /\** * Opens a Socket connected to a remote host at the specified port and * originating from the current host at a system assigned port. * Before returning, {@link #\_connectAction_ \_connectAction\_() } * is called to perform connection initialization actions. *

\* @param hostname The name of the remote host. * @param port The port to connect to on the remote host. * @exception SocketException If the socket timeout could not be set. * @exception IOException If the socket could not be opened. In most * cases you will only want to catch IOException since SocketException is * derived from it. * @exception UnknownHostException If the hostname cannot be resolved. \*/ public void connect(String hostname, int port) throws SocketException, IOException { // 将连接的hostname赋给\_set\_passive\_host \_set\_passive\_host = InetAddress.getByName(hostname).getHostAddress(); \_socket\_= \_socketFactory\_.createSocket(); \_socket\_.connect(new InetSocketAddress(hostname, port), connectTimeout); \_connectAction\_(); } \[/code] ii. org.apache.commons.net.ftp.FTPClient \[code="java"] private void \_\_parsePassiveModeReply(String reply) throws MalformedServerReplyException { java.util.regex.Matcher m = \_\_parms\_pat.matcher(reply); if (!m.find()) { throw new MalformedServerReplyException( "Could not parse passive host information.\\nServer Reply: " + reply); } reply = m.group(); String parts\[] = m.group().split(","); //\_\_passiveHost = parts\[0] + '.' + parts\[1] + '.' + parts\[2] + '.' + parts\[3]; // 此处将\_set\_passive\_host赋给\_\_passiveHost \_\_passiveHost = \_set\_passive\_host; System.out.println("&gt;-----------&gt;&gt; Real Host IP is : "+\_\_passiveHost); try { int oct1 = Integer.parseInt(parts\[4]); int oct2 = Integer.parseInt(parts\[5]); \_\_passivePort = (oct1 &lt;&lt; 8) | oct2; } catch (NumberFormatException e) { throw new MalformedServerReplyException( "Could not parse passive host information.\\nServer Reply: " + reply); } } \[/code]