要获取内网地址,可以尝试连接到10.255.255.255:1。如果连接成功,获取本地套接字的地址信息就是当前的内网IP。
python实现:
import socket
def extract_ip():
st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
st.connect(('10.255.255.255', 1))
IP = st.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
st.close()
return IP
Java:
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* 网络工具
* @author jqpeng
*/
public class NetUtils {
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost.getHostAddress());
System.out.println("----------------下面才是正确的获取方式----------------");
localHost = getLocalHostExactAddress();
System.out.println(localHost.getHostAddress());
// System.out.println(localHost.getHostName());
}
public static InetAddress getLocalHostExactAddress() {
try {
DatagramSocket socket = new DatagramSocket();
socket.connect(InetAddress.getByName("10.255.255.255"), 1);
InetAddress address = socket.getLocalAddress();
socket.close();
return address;
} catch (UnknownHostException | SocketException e) {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
}
}
}
标签:JAVA,socket,python,System,网卡,UnknownHostException,InetAddress,import,localHost
From: https://www.cnblogs.com/xiaoqi/p/get-server-ip.html