① 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());
}
}
② 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發來所有的數據包
額。。。初看到你的問題的時候嚇了一跳。還以為是用java實現網路嗅探呢。
你問的是socket編程?
那麼socket 均分為兩個,
一部分是服務端,
一部分是客戶端,
服務端一直開啟著監聽,
現在你的情況和平時不太一樣的是,平時,是服務端的ip不變化,而客戶端的變化。而是客戶端給服務端進行發送。
你的情況是相反。客戶端經常變動ip或者埠,而要求服務端發送。
其實轉換一下思路就好了。
有點類似於現在網頁在線聊天工具里的「長連接」思想。
你的那個固定ip伺服器,可以完全不管,你是什麼埠。因為,如果你的電腦准備好接受數據了。那麼你就向服務端發起請求。而服務端將結果發送給你。就是說,不是說伺服器一直給你發送,而是,你這個客戶端只要准備好接受數據,就向伺服器發送請求。這樣,不是沒有問題了么。。
如果還按你那個思路就是,你的電腦,需要實現網路嗅探的部分功能。但是
Java是網路層以上的。
你通過Java的Socket得到的數據包嗅探不出什麼敏感的東東了。
所以Java不適合做網路嗅探。
不過還好,現在有了叫jpcap的工具。你可以搜一下,
下面是一個簡單的實現,裡面獲得了來源的ip和埠 你可以加一個判斷,如果來源ip是固定的ip的話,那麼,你可以獲取對應的數據包
本程序用eclipse編輯在J2SDK6.0+WinPcap 3.1+Jpcap 0.5下編譯運行
/*******************
* JpcapTip.java
*/
package m;
import jpcap.PacketReceiver;
import jpcap.JpcapCaptor;
import jpcap.packet.*;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
//import java.net.InetAddress;
//import java.net.UnknownHostException;
public class JpcapTip implements PacketReceiver {
public void receivePacket(Packet packet) {
System.out.println("********************************************");
/*IP數據報報文頭*/
byte[] l=packet.header;
/*
for (int t=0;t<21;t++){
System.out.print(l[t]+" *** ");
}
*/
String str="";
System.out.print("報文頭 : ");
for (int i=0;i<l.length;i++) {
//str=str+l;
int m=0;
m=l[i];
m=m<<24;
m=m>>>24;
str=str+Integer.toHexString(m);
//System.out.print(" *** "+l[i]);
}
System.out.println(str);
int d=l.length;
System.out.println("首部長度 :"+(d*8)+"bit");
/*分析源IP地址和目的IP地址*/
/*分析協議類型*/
/**
if(packet.getClass().equals(IPPacket.class)) {
IPPacket ipPacket=(IPPacket)packet;
byte[] iph=ipPacket.option;
String iphstr=new String(iph);
System.out.println(iphstr);
}
*/
if(packet.getClass().equals(ARPPacket.class))
{
System.out.println("協議類型 :ARP協議");
try {
ARPPacket arpPacket = (ARPPacket)packet;
System.out.println("源網卡MAC地址為 :"+arpPacket.getSenderHardwareAddress());
System.out.println("源IP地址為 :"+arpPacket.getSenderProtocolAddress());
System.out.println("目的網卡MAC地址為 :"+arpPacket.getTargetHardwareAddress());
System.out.println("目的IP地址為 :"+arpPacket.getTargetProtocolAddress());
} catch( Exception e ) {
e.printStackTrace();
}
}
else
if(packet.getClass().equals(UDPPacket.class))
{
System.out.println("協議類型 :UDP協議");
try {
UDPPacket udpPacket = (UDPPacket)packet;
System.out.println("源IP地址為 :"+udpPacket.src_ip);
int tport = udpPacket.src_port;
System.out.println("源埠為:"+tport);
System.out.println("目的IP地址為 :"+udpPacket.dst_ip);
int lport = udpPacket.dst_port;
System.out.println("目的埠為:"+lport);
} catch( Exception e ) {
e.printStackTrace();
}
}
else
if(packet.getClass().equals(TCPPacket.class)) {
System.out.println("協議類型 :TCP協議");
try {
TCPPacket tcpPacket = (TCPPacket)packet;
int tport = tcpPacket.src_port;
System.out.println("源IP地址為 :"+tcpPacket.src_ip);
System.out.println("源埠為:"+tport);
System.out.println("目的IP地址為 :"+tcpPacket.dst_ip);
int lport = tcpPacket.dst_port;
System.out.println("目的埠為:"+lport);
} catch( Exception e ) {
e.printStackTrace();
}
}
else
if(packet.getClass().equals(ICMPPacket.class))
System.out.println("協議類型 :ICMP協議");
else
System.out.println("協議類型 :GGP、EGP、JGP協議或OSPF協議或ISO的第4類運輸協議TP4");
/*IP數據報文數據*/
byte[] k=packet.data;
String str1="";
System.out.print("數據 : ");
for(int i=0;i<k.length;i++) {
//int m=0;
//m=k[i];
//m=m<<24;
//m=m>>>24;
//str1=str+Integer.toHexString(m);
str1 = new String(k);
//str1=str1+k[i];
//System.out.print(" *** "+k[i]);
}
System.out.println(str1);
System.out.println("數據報類型 : "+packet.getClass());
System.out.println("********************************************");
}
public static void main(String[] args) throws Exception{
// TODO 自動生成方法存根
NetworkInterface[] devices = JpcapCaptor.getDeviceList(); //.getDeviceList();.
//for (int i =0; i<devices.length;i++) {
int a=0;
//try {
/*本地網路信息*/
byte[] b=devices[1].mac_address; //網卡物理地址
//}
//catch() {}
System.out.print("網卡MAC : 00");
for (int j=0;j<b.length;j++){
//a=a<<8;
a=b[j];
a=a<<24;
a=a>>>24;
System.out.print(Integer.toHexString(a));
}
System.out.println();
NetworkInterfaceAddress[] k=devices[1].addresses;
//System.out.println("網卡MAC : "+Integer.toHexString(a));
for(int n=0;n<k.length;n++) {
System.out.println("本機IP地址 : "+k[n].address); //本機IP地址
System.out.println("子網掩碼 : "+k[n].subnet); //子網掩碼
}
System.out.println("網路連接類型 : "+devices[1].datalink_description);
//}
NetworkInterface deviceName = devices[1];
/*將網卡設為混雜模式下用網路設備deviceName*/
JpcapCaptor jpcap =JpcapCaptor.openDevice(deviceName, 2000, false, 1); //openDevice(deviceName,1028,false,1);
jpcap.loopPacket(-1,new JpcapTip());
}
}
加油~~
④ java怎麼解析Wireshark抓包文件
Wireshark數據包解析:在Wireshark中關於數據包的叫法有三個術語,分別是幀、包、段。
注意:
如果鏈接另一個Web站點時,客戶端將再次對下一個站點進行DNS查詢(156、157幀),TCP三次握手(158、159、160幀)。
31幀是客戶端請求網路,通過DNS伺服器解析IP地址的過程。標識為「A」記錄。
32幀是DNS伺服器回應客戶端請求的過程。標識為response。
⑤ java網路抓ip包 首部是個什麼情況
首先要去下載jpcap並在IDE上做配置,具體操作方式參考以下鏈接
網頁鏈接
代碼:
importjava.io.IOException;
importjpcap.*;
importjpcap.packet.IPPacket;
importjpcap.packet.Packet;
publicclassTest{
publicstaticvoidmain(String[]args){
/*-------------- 第一步綁定網路設備--------------*/
NetworkInterface[]devices=JpcapCaptor.getDeviceList();
for(NetworkInterfacen:devices){
System.out.println(n.name+"|"+n.description);
}
System.out.println("-------------------------------------------");
JpcapCaptorjpcap=null;
intcaplen=1512;
booleanpromiscCheck=true;
try{
jpcap=JpcapCaptor.openDevice(devices[1],caplen,promiscCheck,50);
//0或1
}catch(IOExceptione){
e.printStackTrace();
}
/*----------第二步抓包-----------------*/
inti=0;
while(i<10){
Packetpacket=jpcap.getPacket();
if(packetinstanceofIPPacket&&((IPPacket)packet).version==4){
i++;
IPPacketip=(IPPacket)packet;//強轉
System.out.println("版本:IPv4");
System.out.println("優先權:"+ip.priority);
System.out.println("區分服務:最大的吞吐量:"+ip.t_flag);
System.out.println("區分服務:最高的可靠性:"+ip.r_flag);
System.out.println("長度:"+ip.length);
System.out.println("標識:"+ip.ident);
System.out.println("DF:Don'tFragment:"+ip.dont_frag);
System.out.println("NF:NoreFragment:"+ip.more_frag);
System.out.println("片偏移:"+ip.offset);
System.out.println("生存時間:"+ip.hop_limit);
Stringprotocol="";
switch(newInteger(ip.protocol)){
case1:
protocol="ICMP";
break;
case2:
protocol="IGMP";
break;
case6:
protocol="TCP";
break;
case8:
protocol="EGP";
break;
case9:
protocol="IGP";
break;
case17:
protocol="UDP";
break;
case41:
protocol="IPv6";
break;
case89:
protocol="OSPF";
break;
default:
break;
}
System.out.println("協議:"+protocol);
System.out.println("源IP"+ip.src_ip.getHostAddress());
System.out.println("目的IP"+ip.dst_ip.getHostAddress());
System.out.println("源主機名:"+ip.src_ip);
System.out.println("目的主機名:"+ip.dst_ip);
System.out.println("----------------------------------------------");
}
}
}
}
~
⑥ 如何獲取區域網內所有IP地址 java代碼
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){}
}
}
}
⑦ 如何用ethereal捕獲ip數據包
一、打開抓包配置項:
1. 通過CaptureOptions,點開抓包選項配置
Ethereal使用方法:[1]開始網路抓包
二、設置抓包配置項
1. 設置抓包的網卡
2. 設置抓包的過濾項:只有滿足條件的數據才會被如棗Ethereal 捕捉,如果不填則
捕捉所有的數據包
Ethereal使用方法:[1]開始網路抓包
三、開始抓包
1. 點擊Capture 按鈕,開始Ethereal 開始抓包
Ethereal使用方法:[1]開始網路抓包渣渣拆
四、停止抓包
1. 點擊停止按鈕,停止抓包
Ethereal使用方法:[1]開始網路抓包
5
五、再次開始抓包
1. 如果不需要重新設置抓包的選項,可以直接點擊CaptureStart 來再次梁指抓包
⑧ java編程:聽說有個叫網路嗅探器的東西,請問原理是 怎麼做出來的啊
Sniffer啊,自己去查,不想大片轉貼了。
主要原理是利用網卡的混雜模式,和乙太網自身的特點進行的。
java寫的話用 JPACAP
Jpcap是一個能夠抓取與發送網路數據包的Java組件。可以使用Jpcap從一個網路介面獲取數據包,然後在Java中對它們進行分析和顯示。同樣也可以通過一個網路介面發送任意數據包。Jpcap當前能夠 捕獲乙太網,IPv4,IPv6,ARP/RARP,TCP,UDP和ICMPv4數據包。
Jpcap實際上並非一個真正去實現對數據鏈路層的控制,而是一個中間件,Jpcap調用wincap/libcap,而給Java語言提供一個公共的介面,從而實現了平台無關性。在官方網站上聲明,Jpcap支持FreeBSD3.x,Linux RedHat6.1, Fedora Core4,Solaris,and Microsoft Windows 2000/XP等系統。
Jpcap的整個結構大體上跟wincap/libpcap是很相像的,例如NetworkInterface類對應wincap的 typedef struct_ADAPTER ADAPTER,getDeviceList()對應pcap_findalldevs()等等。
Jpcap主要的類有如下幾個:
1.NetworkInterface
該類的每一個實例代表一個網路設備,一般就是網卡。這個類只有一些數據成員,除了繼承自java.lang.Object的基本方法以外,沒有定義其它方法。
2.JpcapCaptor
該類提供了一系列靜態方法實現一些基本的功能。該類一個實例代表建立了一個與指定設備的鏈接,可以通過該類的實例來控制設備,例如設定網卡模式、設定過濾關鍵字等等。
3.JpcapSender
該類專門用於控制數據包的發送。
4.Packet
這個是所有其它數據包類的父類。Jpcap所支持的數據包有:
ARPPacket、DatalinkPacket、EthernetPacket、ICMPPacket、IPPacket、TCPPacket、UDPPacket。
⑨ 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(i>0)
{
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 DatagramSocket(int port)模式獲取本地IP地址
給你個小例子希望對你有用
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket();
String s="你好!";
DatagramPacket dp=new DatagramPacket(s.getBytes(),s.getBytes().length,
InetAddress.getByName("192.168.0.98"),8888);
ds.send(dp);
ds.close();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServet
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(8888);
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength())+"from"+
dp.getAddress().getHostAddress()+":"+dp.getPort();
System.out.println(str);
ds.close();
}
}