当前位置:首页 » 编程语言 » 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(); } }

热点内容
如何登录男朋友的微信密码 发布:2025-01-16 07:41:14 浏览:193
宝骏解压流程 发布:2025-01-16 07:35:35 浏览:1
两匹压缩机多少钱 发布:2025-01-16 07:29:19 浏览:634
个人pc搭建游戏服务器 发布:2025-01-16 07:27:09 浏览:969
存储剩余照片 发布:2025-01-16 07:25:01 浏览:49
ftp解除限制上传文件个数 发布:2025-01-16 07:16:26 浏览:347
梯度下降法python 发布:2025-01-16 07:10:43 浏览:520
加载并编译着色器apex 发布:2025-01-16 07:00:08 浏览:59
方舟出售脚本 发布:2025-01-16 06:57:55 浏览:955
钉钉代理服务器Ip地址和瑞口 发布:2025-01-16 06:57:05 浏览:698