javaip
Ⅰ IP 地址排序java
ip.txt就按LZ给的,排序完成后在控制台会输出排序后的,ip.txt里面也会变成排序后的结果,
完整代码(请看注释):
//Test.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
//读入ip.txt文件 我放C盘下面,你可以自己定义位置
BufferedReader br = new BufferedReader(new FileReader("c:/ip.txt"));
List <String> list = new ArrayList<String>();
String str;
//将每条ip都读入list(ip.txt里面,一条IP一行)
while((str=br.readLine())!=null)
list.add(str);
//采用IPComparator的算法进行排序
Collections.sort(list,IPComparator);
//控制输出一下,如果不需要 你可以去掉
for(Object o :list)
System.out.println((String)o);
br.close();
//把排序好的,输出回ip.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("c:/ip.txt"));
for(Object o:list)
{
bw.write((String)o+"\r\n");
bw.flush();
}
bw.close();
}
//后面的内容都是IPComparator算法的东西。
public static int compartTo(String ip1,String ip2){
long[] ip11=parseIp(ip1);
long[] ip22=parseIp(ip2);
long ip1Result=0,ip2Result=0;
for(int i=0;i<4;i++){
ip1Result+=(ip11[i]<<(24-i*8));
}
for(int i=0;i<4;i++){
ip2Result+=(ip22[i]<<(24-i*8));
}
if(ip1Result-ip2Result>0){
return 1;
}else if(ip1Result-ip2Result<0){
return -1;
}else{
return 0;
}
}
public static Comparator IPComparator=new Comparator(){
public int compare(Object ip1, Object ip2) {
return compartTo((String)ip1,(String)ip2);
}
};
private static long[] parseIp(String ip){
ip=ip.replace(".", "#");
long result[]=new long[4];
String[] ip1=ip.split("#");
if(ip!=null){
result[0]=Long.parseLong(ip1[0]);
result[1]=Long.parseLong(ip1[1]);
result[2]=Long.parseLong(ip1[2]);
result[3]=Long.parseLong(ip1[3]);
}
return result;
}
}
Ⅱ 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);
%>
Ⅲ 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);
}
}
Ⅳ java如何更改IP地址
更改IP地址之前,先获取本机的IP地址
public static String getIP(){
String Ip = null;
try {
Ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return Ip;
}
获取到本机ip以后,在进行修改ip地址
// local - 接口名称
// static - 设置使用本地静态配置设置IP地址。
// 10.0.0.9 - 要修改的ip
// 255.0.0.0 - 子网掩码
// 10.0.0.1 - 网关,如果为none: 不设置默认网关。
// 1 -默认网关的跃点数。如果网关设置为 ’none’,则不应设置此字段。
public static void setIP(String newip) throws Exception {
Runtime.getRuntime().exec("netsh interface ip set addr \"本地连接\" static "
+ newip + " 255.0.0.0 10.0.0.1 1");
}
Ⅳ 用JAVA如何实现IP绑定
package src;
import java.io.*;
public class getMac {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ipconfig /all");
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
if (line.indexOf("Physical Address") > 0) {
String MACAddr = line.substring(line.indexOf("-") - 2);
System.out.println("MAC address = [" + MACAddr + "]");
}
} catch (java.io.IOException e) {
System.err.println("IOException " + e.getMessage());
}
}
}
ipconfig是Windows下命令提示符支持的一个命令,可以查询到你的机器的ip等网络配置
Runtime.getRuntime().exec("ipconfig /all"); 就是执行该命令
if (line.indexOf("Physical Address") > 0)表示如果在line中查找到Physical Address,就继续执行if中的语句,否则如果找不到,line.indexOf("Physical Address")的返回值=-1
请多少给点分,谢谢
Ⅵ java IP查询方法
Java编程查询IP地址归属地,可以调用淘宝提供的service查询,并且解析http请求返回的json串,代码如下:
packagegetAddressByIp;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
importnet.sf.json.JSONObject;
publicclassGetAddressByIp
{
/**
*
*@paramIP
*@return
*/
(StringIP){
Stringresout="";
try{
Stringstr=getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+IP);
System.out.println(str);
JSONObjectobj=JSONObject.fromObject(str);
JSONObjectobj2=(JSONObject)obj.get("data");
Stringcode=(String)obj.get("code");
if(code.equals("0")){
resout=obj2.get("country")+"--"+obj2.get("area")+"--"+obj2.get("city")+"--"+obj2.get("isp");
}else{
resout="IP地址有误";
}
}catch(Exceptione){
e.printStackTrace();
resout="获取IP地址异常:"+e.getMessage();
}
returnresout;
}
(StringurlStr)
{
try
{//获取HttpURLConnection连接对象
URLurl=newURL(urlStr);
HttpURLConnectionhttpConn=(HttpURLConnection)url.openConnection();
//设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
//获取相应码
intrespCode=httpConn.getResponseCode();
if(respCode==200)
{
returnConvertStream2Json(httpConn.getInputStream());
}
}
catch(MalformedURLExceptione)
{
e.printStackTrace();
}
catch(IOExceptione)
{
e.printStackTrace();
}
return"";
}
(InputStreaminputStream)
{
StringjsonStr="";
//ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStreamout=newByteArrayOutputStream();
byte[]buffer=newbyte[1024];
intlen=0;
//将输入流转移到内存输出流中
try
{
while((len=inputStream.read(buffer,0,buffer.length))!=-1)
{
out.write(buffer,0,len);
}
//将内存流转换为字符串
jsonStr=newString(out.toByteArray());
}
catch(IOExceptione)
{
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnjsonStr;
}
}
Ⅶ 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;
}
}
}
Ⅷ java获得IP地址
简单实现代码如下:
js获取来源页地址方法:
var url = document.referrer;
document.write(url);
jsp获取来源页地址方法:
String url = request.getHeader(”Referer”);
System.out.println(url);
对比两个方法:
1.js里是”referrer”,jsp里是”referer”,前者比后者多一个”r”;
2.前者如直接输入网址,则显示为空,后者显示null;
import java.net.*;
public class ip5 {
public static void main(String args[]) throws Exception {
String ip = InetAddress.getLocalHost().getHostAddress();
System.out.println(ip);
}
}