I was just looking around to find out how to make a program that would sniff my network traffic in Java, but I couldn't find anything. I wanted to know if there was any way to view the network traffic going by. I heard of an idea with a Socket, but I don't get how that would work. So anyways, just looking for an API or a way to write it myself.
EDIT:
I would gladly like an API, but I would also like clarification on the way to sniff traffic with a Socket.
jpcap, jNetPcap -- those are pcap wrapper projects in Java.
Kraken -- similar project, well documented with lots of examples.
simple example from the Kraken web site:
public static void main(String[] args) throws Exception {
File f = new File("sample.pcap");
EthernetDecoder eth = new EthernetDecoder();
IpDecoder ip = new IpDecoder();
TcpDecoder tcp = new TcpDecoder(new TcpPortProtocolMapper());
UdpDecoder udp = new UdpDecoder(new UdpPortProtocolMapper());
eth.register(EthernetType.IPV4, ip);
ip.register(InternetProtocol.TCP, tcp);
ip.register(InternetProtocol.UDP, udp);
PcapInputStream is = new PcapFileInputStream(f);
while (true) {
// getPacket() will throws EOFException and you should call is.close()
PcapPacket packet = is.getPacket();
eth.decode(packet);
}
}
Another Java libpcap wrapper is https://github.com/kaitoy/pcap4j
Pcap4J is a Java library for capturing, crafting and sending packets. Pcap4J wraps a native packet capture library (libpcap or WinPcap) via JNA and provides you Java-Oriented APIs.
You need a packet sniffer api, maybe netutils is what you need:
The 'netutils' package gives a low level java network library. It
contains extensive infrastructure for sniffing, injecting, building
and parsing Ethernet/IP/TCP/UDP/ICMP packets.
Not telling any API or java related thing but if you really want to only sniff data for analysis purpose then give try: WireShark. Its an application used for network analyse.
Its useful if someone is not aware of.
Related
I've always used either ActiveMQ or RabbitMQ, but have started digging into ZeroMQ lately because of the attention its getting. If what I'm reading is correct, then it seems to be a message broker as well as a mechanism for interprocess communication (IPC)?
I have a situation where I have 2 Java processes that need to communicate with each other on the same machine. I don't want to use a shared file approach because the dialog/protocol between them is pretty sophisticated and a file solution seems clumsy.
So I was going to start heading down the road of using something like Netty or MINA to defines my own comm protocol, and have them converse over ports, but then I started reading about ZeroMQ and am wondering if I can accomplish the same but with less work.
So I ask: can ZeroMQ be used for IPC between the Java processes, and if so, are there any concrete code examples or articles explaining exactly how to do this?
The first three lines of the web site tell you every thing you need to know.
Distributed Computing Made Simple
Ø The socket library that acts as a concurrency framework.
Ø Carries messages across inproc, IPC, TCP, and multicast.
I don't see any reason to suspect that this doesn't work over loopback, and it would be pretty bizzare if it couldn't.
Yes, zmq can be used to connect two Java processes. You can use pure Java implementation JeroMq or ZeroMq with Java client. JeroMq is easier to install as you need only the appropriate dependency. Here is simple example for listener:
import org.zeromq.ZMQ;
public class Subscriber {
public static void main(String[] a){
final ZMQ.Context ctx = ZMQ.context(1);
final ZMQ.Socket sub = ctx.socket(ZMQ.SUB);
// sub.connect("tcp://localhost:6001");
sub.connect("ipc://001");
sub.subscribe("".getBytes());
while (true){
String msg = sub.recvStr();
System.out.println(msg);
}
}
}
and for publisher:
import org.zeromq.ZMQ;
public class Publisher {
public static void main(String[] a) throws InterruptedException {
final ZMQ.Context ctx = ZMQ.context(1);
final ZMQ.Socket pub = ctx.socket(ZMQ.PUB);
pub.bind("ipc://001");
// pub.bind("tcp://*:6001");
while (true){
System.out.println("Publishing");
pub.send("Test");
Thread.sleep(1000);
}
}
}
IPC and TCP both work.
I wrote an application in MATLAB to open a UDP socket and listen for incoming datagrams. Basically, something like this:
u = udp(rHost, rPort, 'LocalHost', lHost, 'LocalPort', lPort);
u.DatagramAvailableFcn = #(o,e) operateOnData(o,e);
fopen(u);
This works wonderfully when I'm listening to something in a unicast fashion. But I would now like to be able to listen to multicast traffic. Apparently, this isn't possible in MATLAB.
The workaround is, per above link,
As a workaround to connect to a UDP multicast, you can do the following:
Use a Java multicast socket to access it directly from MATLAB. For more information, see javadoc or tutorials for the "core java.net" classes from Sun, specifically "java.net.MulticastSocket". This could be found at:
http://java.sun.com/j2se/1.4.2/docs/api/java/net/MulticastSocket.html
I have no background in Java so this is a struggle for me. I've only been able to run the following to instantiate a MulticastSocket object:
>> ms = javaObject('java.net.MulticastSocket');
I looked around and found that I also need a java.net.Datagram object to actually contain the incoming stream.
How do I use the MulticastSocket and Datagram objects within the context of MATLAB? I'm trying to replicate the functionality of u.DatagramAvailableFcn, i.e., fire a callback to operate on the contents of the datagram once I receive one.
EDIT: Looks like this is how I want to go about this in terms of the Java, but now it's getting this back into MATLAB-land...
I successfully subscribed and received a packet from a multicast stream, by the following:
socket = java.net.MultiSocket(streamPort);
socket.joinGroup(java.net.InetAddress.getByName(streamIP));
socket.setReuseAddress(1);
packet = java.net.DatagramPacket(zeros(1, intmax('uint16'), 'int8'), intmax('uint16'));
socket.receive(packet);
socket.leaveGroup(InetAddress.getByName(streamIP));
socket.close;
msg = packet.getData;
msg = msg(1:packet.getLength);
This was essentially lifted from judp availble on the MathWorks File Exchange.
I am still looking for a way to get some equivalent of a DatagramReceivedFcn - right now it looks like the socket.receive call is blocking until it times out. I can use timer objects to fire the "callback" on a regular basis but that's of course not the same as having a DatagramReceivedFcn.
I want to make simple android app in which i simply have textview, and a button. on clicking that button, string in textview is broadcast and received at PC. am new to android programming and network programming.
1. Please suggest what tool to be used in PC.
2. Some simple steps to achieve this.
3. some healthy tutorials to understand things better.
Sorry if i sound stupid :P
Thanks in advance.
Welcome to StackOverflow!
Well it sounds like you want to jump into the world of programming Android head first. That's fine but you should start somewhere. The best series of tutorials I've seen to date is at The New Boston. The videos are very easy to understand and the series is made of 200 videos. It covers everything from downloading and installing Eclipse (which is one tool you can use to develop Android apps) all the way to some pretty advanced concepts. So if you have a basic understanding you can pick and choose which videos you want to watch, if you want a full crash course just watch them all. It also has around 3000 other videos on all programming languages. Such as Java which you will need if you don't already know.
On the P.C. side if you don't have any live servers set up to play with I suggest downloading XAMPP at this link XAMPP. It allows you to create a number of things on your own computer, all of which are free. Such as a SQL database with phpmyadmin and a number of other things. All in all if you watch even a few of the 200 videos at The New Boston you will have a much better understanding of what you need to do to accomplish your goals. You will also have a better understanding of what to ask for specifically in the future. Hope this helps, if you need anything else just ask
Well, i'm not sure if this is the best way but still is a way, you could use SMB for android, and for the PC just a normal Java program so:
1: for PC you could use Java (since you use Java as a topic i supose that you know how to do a single program with this programming language
as a suggestion for achieve number 1, you could do a program that every 3-5 seconds constantly check if a empty File have data or still empty and if it has data then show a Dialog with the data, a showMessageDialog would do the job.
2: for android use what i said first, with that you could read or write a File on the PC from your android device, of course if both the PC and android device are in the same network
at this point, just write the String of the TextView or EditText in the File on the PC being checked by the java program, let me know if this help you or if you want more specific details, but i think with this you could do what you want. Sorry for my English, still learning it :)
It sounds like sockets would be good for what you want to do.Basically, you'll need to have a server script/program running on the PC and the android program can send a connection request and then a packet with the string.
You'll need to create a ServerSocket with something like this on the server and have it listen on a port of your choosing.
ServerSocket serverSocket = null;
int port = 9876;
try {
serverSocket = new ServerSocket(port);
} catch ( Exception e ) {
System.out.printf("Could not listen on port: %d", port );
System.exit(-1);
}
Often a new thread is used to accept the connection like this.
new Thread(new ServerThread(serverSocket.accept())).start();
The run() method of the ServerThread can be as simple as this
try {
Scanner socketIn = new Scanner(this.clientSocket.getInputStream());
PrintWriter socketOut = new
PrintWriter(this.clientSocket.getOutputStream(), true);
while(socketIn.hasNext() {
System.out.println(socketIn.next());
}
} catch (Exception e) {
}
You can create a socket on the client side (in your case on the android device) with code like this. (Note that android won't let you do this in your main thread so you'll have to create the connection in another thread.
public void sendRequest(final String message) {
Log.d("test", "log");
new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket(InetAddress.getByName(HOST), PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (Exception e) {
Log.d("Exception in thread", e.getStackTrace()+"");
}
}
}.start();
}
Since you're just doing this on your wifi, instead of InetAddress.getByName(HOST), you can just put the local IP address of the PC. Also, if you are planning on this working always, rather than just learning and practicing around, it would be good to set up the PC with a static local IP on your network. There are plenty of tutorials for doing that on different OSs out there.
Fortunately, socket programming in java is pretty simple. You can use the Scanner and Printwriter to read and write to sockets.
Please note that I have not tested the above code, but the principle is sound.
Here are a few sites with some info.
http://cs.lmu.edu/~ray/notes/javanetexamples/
http://docs.oracle.com/javase/tutorial/networking/sockets/ I like this one
Edit. I could only post two of the links because my rep is low.
I'm working on mobile ipv6 in java and want to make custom ipv6 packets.
how do I write class to make ipv6 packets and I put the payload myself?
Following is the example of the similar class:
CustomIPv6 ipv6 = new CustomIPv6();
ipv6.setSource("::1");
ipv6.setDestination("::1");
ipv6.setPayload(MyArrayOfByte); //The byte array which I made it myself. -> the mobile ipv6 extention
ipv6.setUpperLayerType(CustomIPv6.MobilityHeader);
ipv6.sendPacket();
byte[] recv = ipv6.ReceivPacket();
//Now is the time for process the received packet and send some kind of ack.
Thanks all friends in advance.
You can do this with http://jnetpcap.com/ however it requires libpcap or winpcap be installed. This facility is useful for network hacking which could be why it is not better supported. ;)
I'm using Clojure, but I can read Java, so this isn't a Clojure specific question. This doesn't even seem to be working from Java.
I'm trying to implement a bit of a 'ping' function using isReachable. The code I'm using is this:
(.isReachable (java.net.InetAddress/getByName "www.microsoft.com") 5000)
Translated to Java by a good friend of mine:
public class NetTest {
public static void main (String[] args) throws Exception{
String host = "acidrayne.net";
InetAddress a = InetAddress.getByName(host);
System.out.println(a.isReachable(10000));
}
}
Both of these return false. I suppose I must be doin' it wrong, but Google research is telling me differently. I'm confuzzled!
Updated in response to comment that this is wrong:
Using Unix/Linux??
http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html says:
Linux/Unix, instead, supports an ICMP "ping" system call. So the implementation of java.net.InetAddress.isReachable() first tries to perform the "ping" system call**; if this fails, it falls back trying to open a TCP socket on [sic - to] port 7, as in Windows.
It turns out that in Linux/Unix the ping system call requires root privileges, so most of the times java.net.InetAddress.isReachable() will fail, because many Java programs are not run as root, and because the target address unlikely has the echo service up and running. Too bad.
The comment below from #EJP indicates the part of about the echo service is wrong, wrong wrong:
That's not correct. isReachable returns true if it gets a ConnectException trying to connect to port 7, as that proves that the host is up and able to send RST segments.
In cases like these, I use a packet sniffer like WireShark, tcpdump (WinDump on Windows) or snoop (Solaris) to confirm what is really happening on the wire.
The correct answer is not actually correct I think. Microsoft.com simply ignore ICMP requests, probably to avoid basic ping flood attacks. As for the second host I've no idea what the problem with the ping might be, but I'm using GNU/Linux and isReachable works just fine.