Debian Java網絡設置需分別配置系統網絡接口和Java應用程序參數,具體步驟如下:
使用命令 ip addr 或 ifconfig 確認網絡接口名稱(如 eth0、wlan0)。
sudo nano /etc/netplan/01-netcfg.yamlsudo nano /etc/network/interfaces# Netplan配置(Debian 10+)
network:
version: 2
ethernets:
eth0:
dhcp4: no
addresses: [192.168.1.100/24]
gateway4: 192.168.1.1
nameservers:
addresses: [8.8.8.8, 8.8.4.4]
或(舊版本):# interfaces配置
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
sudo netplan applysudo systemctl restart networking使用 ping www.google.com 確認網絡連通性。
在Java代碼中通過 System.setProperty 配置代理或網絡參數:
// 設置HTTP/HTTPS代理
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
Socket socket = new Socket("192.168.1.100", 8080);
URL 類訪問網絡資源。URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Java默認使用系統DNS配置(需確保 /etc/resolv.conf 正確),無需在代碼中額外設置。
Netplan,舊版本使用 /etc/network/interfaces。dhcp 即可,無需手動指定IP。參考來源: