java获取本地外网ip地址

mac2025-03-22  17

获取本机外网ip地址

public static String getIP() { String ip = "http://pv.sohu.com/cityjson?ie=utf-8"; String inputLine = ""; String read = ""; String toIp=""; try { URL url = new URL(ip); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((read = in.readLine()) != null) { inputLine += read; } String ObjJson=inputLine.substring(inputLine.indexOf("=")+1,inputLine.length()-1); // System.out.println(ObjJson); JSONObject jsonObj= JSON.parseObject(ObjJson); toIp=jsonObj.getString("cip"); // throw new Exception(); } catch (Exception e) { toIp=""; } return toIp; }

获取服务器IP地址

/** * 根据域名获取ip地址 */ public static String getIfIP() { String toIp=""; try{ String pathName="baidu.com";//这里没有进行支持https协议的,可以自行进行切割字符串 InetAddress address =InetAddress.getAllByName(pathName)[0]; toIp=address.getHostAddress(); }catch (Exception e){ toIp=""; } return toIp; }
最新回复(0)