當前位置:首頁 » 編程語言 » ipjava

ipjava

發布時間: 2022-08-31 07:22:50

1. java 如何驗證ip地址

可以使用正則表達式驗證ip地址,ip地址分為v4和v6兩個版本,v4為32位,分4段,中間用.隔開,v6為128位,可分為4段32位中間用::隔開。

以下是驗證類詳細代碼:
import java.util.regex.Pattern;
/**
* A collection of utilities relating to InetAddresses.
*/
public class InetAddressUtils {
public static void main(String[] args){
String addr="192.168.1.2";
System.out.println(isIPv4Address(addr));
}

private static final Pattern IPV4_PATTERN =
Pattern.compile(
"^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

private static final Pattern IPV6_STD_PATTERN =
Pattern.compile(
"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");

private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
Pattern.compile(
"^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
}

public static boolean isIPv6StdAddress(final String input) {
return IPV6_STD_PATTERN.matcher(input).matches();
}

public static boolean isIPv6HexCompressedAddress(final String input) {
return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
}

public static boolean isIPv6Address(final String input) {
return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
}
}

2. JAVA怎麼獲取IP地址

java代碼獲取ip地址方法是
調用java.net包下面的的InetAddress類獲取。

3. Java怎樣獲取當前機器外網IP

java獲取本機的外網ip示例:
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 獲取本機外網IP地址
* 思想是訪問網站http://checkip.dyndns.org/,得到返回的文本後解析出本機在外網的IP地址
* @author pieryon
*
*/
public class ExternalIpAddressFetcher {
// 外網IP提供者的網址
private String externalIpProviderUrl;

// 本機外網IP地址
private String myExternalIpAddress;

public ExternalIpAddressFetcher(String externalIpProviderUrl) {
this.externalIpProviderUrl = externalIpProviderUrl;

String returnedhtml = fetchExternalIpProviderHTML(externalIpProviderUrl);

parse(returnedhtml);
}

/**
* 從外網提供者處獲得包含本機外網地址的字元串
* 從http://checkip.dyndns.org返回的字元串如下
* <html><head><title>Current IP Check</title></head><body>Current IP Address: 123.147.226.222</body></html>
* @param externalIpProviderUrl
* @return
*/
private String fetchExternalIpProviderHTML(String externalIpProviderUrl) {
// 輸入流
InputStream in = null;

// 到外網提供者的Http連接
HttpURLConnection httpConn = null;

try {
// 打開連接
URL url = new URL(externalIpProviderUrl);
httpConn = (HttpURLConnection) url.openConnection();

// 連接設置
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");

// 獲取連接的輸入流
in = httpConn.getInputStream();
byte[] bytes=new byte[1024];// 此大小可根據實際情況調整

// 讀取到數組中
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}

// 將位元組轉化為為UTF-8的字元串
String receivedString=new String(bytes,"UTF-8");

// 返回
return receivedString;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
httpConn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}

// 出現異常則返回空
return null;
}

/**
* 使用正則表達式解析返回的HTML文本,得到本機外網地址
* @param html
*/
private void parse(String html){
Pattern pattern=Pattern.compile("(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})", Pattern.CASE_INSENSITIVE);
Matcher matcher=pattern.matcher(html);
while(matcher.find()){
myExternalIpAddress=matcher.group(0);
}
}

/**
* 得到本機外網地址,得不到則為空
* @return
*/
public String getMyExternalIpAddress() {
return myExternalIpAddress;
}

public static void main(String[] args){
ExternalIpAddressFetcher fetcher=new ExternalIpAddressFetcher("http://checkip.dyndns.org/");

System.out.println(fetcher.getMyExternalIpAddress());
}
}

4. java怎麼獲取請求的ip

java獲取外網ip地址方法:
public class Main {

public static void main(String[] args) throws SocketException {
System.out.println(Main.getRealIp());
}

public static String getRealIp() throws SocketException {
String localip = null;// 本地IP,如果沒有配置外網IP則返回它
String netip = null;// 外網IP

Enumeration<NetworkInterface> netInterfaces =
NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外網IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 外網IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 內網IP
localip = ip.getHostAddress();
}
}
}

if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
}

5. java中獲取本地IP地址

方法如下:
方法一,使用CMD命令:
public static String getLocalIPForCMD(){
StringBuilder sb = new StringBuilder();
String command = "cmd.exe /c ipconfig | findstr IPv4";
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = br.readLine()) != null){
line = line.substring(line.lastIndexOf(":")+2,line.length());
sb.append(line);
}
br.close();
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
方法二,使用Java方法:
public static String getLocalIPForJava(){
StringBuilder sb = new StringBuilder();
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
&& inetAddress.isSiteLocalAddress()) {
sb.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException e) { }
return sb.toString();
}

6. JAVA如何限制用戶IP地址

java web中限制訪問的ip,主要是使用session的getRemortIP(HttpServletRequest)方法,如下代碼:

/**
*
*@paramrequest
*@return
*
*功能:得到用戶Ip地址
*/
publicstaticStringgetRemortIP(HttpServletRequestrequest){
if(request.getHeader("x-forwarded-for")==null){
returnrequest.getRemoteAddr();
}
returnrequest.getHeader("x-forwarded-for");
}

調用

Stringip=getRemortIP(HttpServletRequest);
if(ip=="127.0.0.1"){
System.out.print("禁止訪問");
}

Hr完整項目中---common.jsp得到網址

<%
//路徑
Stringpath=request.getContextPath();
//request保存
request.setAttribute("path",path);
%>

7. java 如何獲取指定ip數據

  1. String userIp = request.getRemoteAddr();

  2. if (userIp.equals("目標ip")) {

  3. //TODO 獲取需要的數據

  4. }else {

  5. //TODO 不滿足條件,做其他處理

  6. }

8. java如何獲取區域網內所有IP

1.得到區域網網段,可由自己機器的IP來確定 (也可以手動獲取主機IP-CMD-ipconfig /all)
2.根據IP類型,一次遍歷區域網內IP地址
JAVA類,編譯之後直接運行便可以得到區域網內所有IP,具體怎樣使用你自己編寫相應代碼調用便可
代碼如下::
package bean;

import java.io.*;
import java.util.*;

public class Ip{
static public HashMap ping; //ping 後的結果集
public HashMap getPing(){ //用來得到ping後的結果集
return ping;
}

//當前線程的數量, 防止過多線程摧毀電腦
static int threadCount = 0;

public Ip() {
ping = new HashMap();
}

public void Ping(String ip) throws Exception{
//最多30個線程
while(threadCount>30)
Thread.sleep(50);
threadCount +=1;
PingIp p = new PingIp(ip);
p.start();
}

public void PingAll() throws Exception{
//首先得到本機的IP,得到網段
InetAddress host = InetAddress.getLocalHost();
String hostAddress = host.getHostAddress();
int k=0;
k=hostAddress.lastIndexOf(".");
String ss = hostAddress.substring(0,k+1);
for(int i=1;i <=255;i++){ //對所有區域網Ip
String iip=ss+i;
Ping(iip);
}

//等著所有Ping結束
while(threadCount>0)
Thread.sleep(50);
}

public static void main(String[] args) throws Exception{
Ip ip= new Ip();
ip.PingAll();
java.util.Set entries = ping.entrySet();
Iterator iter=entries.iterator();

String k;
while(iter.hasNext()){
Map.Entry entry=(Map.Entry)iter.next();
String key=(String)entry.getKey();
String value=(String)entry.getValue();

if(value.equals("true"))
System.out.println(key+"-->"+value);
}
}
class PingIp extends Thread{
public String ip; // IP
public PingIp(String ip){
this.ip=ip;
}

public void run(){
try{
Process p= Runtime.getRuntime().exec ("ping "+ip+ " -w 300 -n 1");
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader (ir);
//讀取結果行
for (int i=1 ; i <7; i++)
input.readLine();
String line= input.readLine();

if (line.length() <17 || line.substring(8,17).equals("timed out"))
ping.put(ip,"false");
else
ping.put(ip,"true");
//線程結束
threadCount -= 1;
}catch (IOException e){}
}
}
}

9. java怎麼獲取ip地址

java獲取ip地址
public static void main(String[] args) { try { // 獲取計算機名 String name = InetAddress.getLocalHost().getHostName(); // 獲取IP地址 String ip = InetAddress.getLocalHost().getHostAddress(); System.out.println("計算機名:"+name); System.out.println("IP地址:"+ip); } catch (UnknownHostException e) { System.out.println("異常:" + e); e.printStackTrace(); } }

熱點內容
fmp腳本 發布:2025-01-16 08:12:23 瀏覽:230
nagios自定義腳本 發布:2025-01-16 08:09:52 瀏覽:364
安卓為什麼下不了方舟生存進化 發布:2025-01-16 08:02:32 瀏覽:194
如何登錄男朋友的微信密碼 發布:2025-01-16 07:41:14 瀏覽:194
寶駿解壓流程 發布:2025-01-16 07:35:35 瀏覽:2
兩匹壓縮機多少錢 發布:2025-01-16 07:29:19 瀏覽:635
個人pc搭建游戲伺服器 發布:2025-01-16 07:27:09 瀏覽:970
存儲剩餘照片 發布:2025-01-16 07:25:01 瀏覽:50
ftp解除限制上傳文件個數 發布:2025-01-16 07:16:26 瀏覽:348
梯度下降法python 發布:2025-01-16 07:10:43 瀏覽:520