java 获取本地ip,更改ip。并附上java程序打jar包,做exe文件的全过程
时间: 2024-06-08 22:08:31 浏览: 50
获取本地IP的Java代码:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetLocalIP {
public static void main(String[] args) throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: "+addr.getHostAddress());
}
}
```
更改本地IP的Java代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ChangeLocalIP {
public static void main(String[] args) {
List<String> commandList = new ArrayList<String>();
commandList.add("netsh");
commandList.add("interface");
commandList.add("ipv4");
commandList.add("set");
commandList.add("address");
commandList.add("name=\"以太网\"", "static", "192.168.1.100", "255.255.255.0", "192.168.1.1");
try {
ProcessBuilder builder = new ProcessBuilder(commandList);
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
打包jar文件:
```bash
javac GetLocalIP.java
jar cvfm GetLocalIP.jar manifest.txt GetLocalIP.class
```
其中,`manifest.txt` 的内容如下:
```
Main-Class: GetLocalIP
```
打包exe文件:
1. 在 Windows 系统上安装 Launch4j(http://launch4j.sourceforge.net/)。
2. 使用 Launch4j 创建一个 XML 配置文件,如下:
```xml
<launch4jConfig>
<headerType>gui</headerType>
<jar>D:\workspace\GetLocalIP.jar</jar>
<outfile>D:\workspace\GetLocalIP.exe</outfile>
<errTitle></errTitle>
<classPath>
<mainClass>GetLocalIP</mainClass>
<preCp>anything</preCp>
</classPath>
<jre>
<minVersion>1.6.0</minVersion>
<jdkPreference>preferJre</jdkPreference>
</jre>
<versionInfo>
<fileVersion>1.0.0.0</fileVersion>
<txtFileVersion>1.0.0</txtFileVersion>
<fileDescription>GetLocalIP</fileDescription>
<productVersion>1.0.0.0</productVersion>
<txtProductVersion>1.0.0</txtProductVersion>
<productName>GetLocalIP</productName>
<companyName>My Company Name</companyName>
<internalName>GetLocalIP</internalName>
<originalFilename>GetLocalIP.exe</originalFilename>
</versionInfo>
</launch4jConfig>
```
3. 在 Launch4j 窗口中加载这个 XML 配置文件并生成 exe 文件。
阅读全文