「java生成ip」java生成id的方法
今天给各位分享java生成ip的知识,其中也会对java生成id的方法进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
java获得IP地址
下面有一篇文章,介绍若何读取物理网卡的地址 ,同样的
你可以用这个方法读取你所需要的本机IP地址
=======================================================
J2SE5.0新特性之ProcessBuilder
这个例子使用了J2SE5.0的ProcessBuilder类执行外部的程序,相对于 Runtime.exec ,它更方便,可以设置环境变量等。这里使用它在windows下读取物理网卡的地址
package com.kuaff.jdk5package;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ProcessBuilderShow
{
public static List getPhysicalAddress()
{
Process p = null;
//物理网卡列表
List address = new ArrayList();
try
{
//执行ipconfig /all命令
p = new ProcessBuilder("ipconfig", "/all").start();
}
catch (IOException e)
{
return address;
}
byte[] b = new byte[1024];
StringBuffer sb = new StringBuffer();
//读取进程输出值
InputStream in = p.getInputStream();
try
{
while (in.read(b)0)
{
sb.append(new String(b));
}
}
catch (IOException e1)
{
}
finally
{
try
{
in.close();
}
catch (IOException e2)
{
}
}
//以下分析输出值,得到物理网卡
String rtValue = sb.substring(0);
int i = rtValue.indexOf("Physical Address. . . . . . . . . :");
while(i0)
{
rtValue = rtValue.substring(i + "Physical Address. . . . . . . . . :".length());
address.add(rtValue.substring(0,18));
i = rtValue.indexOf("Physical Address. . . . . . . . . :");
}
return address;
}
public static void main(String[] args)
{
List address = ProcessBuilderShow.getPhysicalAddress();
for(String add:address)
{
System.out.printf("物理网卡地址:%s%n", add);
}
}
}
JAVA怎么获取IP地址
这个是获取不到的,因为有代理、端口映射等等转发情况的存在。为什么不保存相对路径/域名/或者在服务器上某个配置文件中配置域名/数据库中一个表/数据库中某个字段保存当前服务器的ip地址呢?
java如何获取公网ip,有通过路由
如果要通过路由器,不同的路由器的获取方法不一样。通用的做法是通过 HttpClient 在百度上搜索关键字 ip, 然后提取出公网ip。
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class App {
// 获取网页源码
static String httpGet(String url) {
StringBuffer buffer = new StringBuffer();
try {
URLConnection conn = new URL(url).openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
try (InputStream inputStream = conn.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);) {
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line).append(System.lineSeparator());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
String html = httpGet("");
// 提出IP
Pattern pattern = Pattern.compile("span\\sclass=\"c-gap-right\"本机IP:nbsp;([^]+)/span");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String ip = matcher.group(1);
System.out.println(ip);
}
}
}
java生成ip的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java生成id的方法、java生成ip的信息别忘了在本站进行查找喔。