How to test connectivity to ports - java

I'm still a beginning programmer but I like to experiment and learn while practicing. I play League of Legends a lot, this is the biggest online game today. Sometimes the server of this game are offline and my idea was to make a java programm that checks wether the game is online (ports are open) and then tells me if the game is online or not. Due to me being a beginner programmer and my understanding of ports/network adresses still lack a bit, I wonder if someone could explain or help me achieving my goal. If it is by explaining or providing helpfull links, I'm open to everything!
Thanks in advance,
Boris

There are some tools that you can check that whether the server is alive or not.
The most basic one is ping in CMD:
ping stackoverflow.com (if you have domain)
or
ping 198.252.206.16 (if you have IP)
if you see sth like this so server is alive and give a response:
Ping statistics for 198.252.206.16:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 142ms, Maximum = 145ms, Average = 143ms
But if you see this, then server or your internet connection has a problem:
Request timed out.
There are some other tools such as Hercules to test a server alive or not.
If you are still sure to write a program yourself in java, you can try to create a new java.net.Socket. If that line throws any exception then you are not able to connect to the server. To manage this, you should use "try-catch" blocks.

You can use java socket to detect the port is alive or dead:
import java.io.IOException;
import java.net.Socket;
public class PortDetect {
public static void main(String[] args) {
try {
new Socket("1.2.3.4", 8080);
System.out.println("alive");
} catch (IOException e) {
e.printStackTrace();
System.out.println("dead");
}
}
}

Related

Stuck at socket.accept()

Hello I just started a Java Enterprise Edition class. This is my first exposure to this side of java programming so this is all pretty new to me. I was reading my textbook and decided to type it one of the codes given to me to try it out. This code is not mine. The program should output "hello, enter BYE to exit" and then echo back anything that is typed into the prompt. For some reason the code hangs at the try block containing s.accept (it outputs 1 then 2 then hangs). I was just wondering if anyone would have any insight as to why this isnt working for me when i copied it exactly from my textbook. Here is the code:
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoServer
{
public static void main (String[] args) throws IOException
{
System.out.println("1");
try (ServerSocket s = new ServerSocket(8189))
{
System.out.println("2");
try(Socket incoming = s.accept())
{
System.out.println("3");
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
try(Scanner in = new Scanner(inStream))
{
PrintWriter out = new PrintWriter(outStream,true);
out.println("Hello! Enter BYE to exit.");
boolean done = false;
while(!done && in.hasNextLine())
{
String line = in.nextLine();
out.println("Echo: " + line);
if(line.trim().equals("BYE"))
done = true;
}
}
}
}
}
}
Im sure this is something relatively simple to explain, im just new to this and was wondering why this isnt working when i try to run it.
Is there a corresponding EchoClient demo in the textbook?
Socket.accept() hangs by design until a client connects to the port that is being waited on, in this case, port 8189. Your program is working fine
If you read the documentation you will see that Socket.accept() actually hangs the thread until a client connect , so after the connection is established it will continue also your using an echo protocol , so you need to make sure that the client in this case is ANOTHER server that supports echo protocol
You're dealing with networking. Great. Let's distinguish between terms a bit.
socket.accept() is an example of a blocking function call. I can't find any link to provide a quick interpretation but, to oversimplify, your code stops at that point until some event it is waiting for finally happens, in this case, a connection from a corresponding client. Hence, its behaving normally, as expected, as documented. You'll encounter lots of other blocking function calls waiting for all sorts of events like an item is inserted to a queue, threads finish processing, etc.
In contrast, the word "hang" as normally used, refers to a deadlock or (less commonly), kernel panic. This is usually a mistake on the programmer's part.

send stringt from android over wifi and recieve in PC(java program)

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.

Java TCP Client/Server

I have a problem which I do not know how to proceed further in Java TCP socket issue. So far as what we can get from the Internet, it's not hard to get quite a number of working solution for TCP server & client communication in Java. However, most of the example will have their server listen to a port, and then loop until they get a client which connects to the server, then the code will perform server.accept() and move further. For example:
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
try {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
System.out.println("Connection accepted: "+ socket);
It will work perfectly if there's a client connecting to the server. And, my problem is that I need to continue some other procedures even though there's no client connecting to the server. In fact, I will need to launch another JFrame to continue the procedures even if there is no client connecting to the same port and ip. However, I have been struggling but as long as there is not client connecting to the server, my Java program will hang there with white popped up JFrame.
I would need to know how to overcome this as I am not quite sure whether there's a mistake in my understanding. Please assist and advice. Thank you!
Best Regards,
Yi Ying
Sounds like you need to do work in one thread whilst waiting for network connections on another. Check out the threading tutorial. Note that since you're using Swing, you have to be careful wrt. which thread will modify your JFrame etc. and you should be aware of the SwingWorker utility.

My ISP is forcing me to buffer tcp data before sending it

I have a Java TCP game server, I use java.net.ServerSocket and everything runs just fine, but recently my ISP did a some kind of an upgrade, where, if you send two packets very fast for the same TCP connexion, they close it by force.
This is why a lot of my players are disconnected randomly when there's a lot of traffic in game (when there is a lot of chance that the server will send 2 packets at same time for the same person)
Here is an example of what I mean:
If I do something like this, my ISP will close the connexion for no reason to both client and server side:
tcpOut.print("Hello.");
tcpOut.flush();
tcpOut.print("How are you?");
tcpOut.flush();
But it will work just fine if i do something like this:
tcpOut.print("Hello.");
tcpOut.flush();
Thread.sleep(200);
tcpOut.print("How are you?");
tcpOut.flush();
Or this:
tcpOut.print("Hello.");
tcpOut.print("How are you?");
tcpOut.flush();
This only started a couple of weeks ago when they (the ISP) did some changes to the service and the network. I noticed using Wireshark that you have to have at least ~150ms time between two packets for same TCP connexion or else it will close.
1)Do you guys know what is this called ? does is it even have a name ? Is it legal ?
Now I have to re-write my game server knowing that I use a method called: send(PrintWriter out, String packetData);
2)Is there any easy solution to ask java to buffer the data before it sends it to clients ? Or wait 150ms before each sending without having to rewrite the whole thing ? I did some googling but I can't find anything that deals with this problem. Any tips or information to help about this would be really appreciated, btw speed optimisation is very crucial. Thank you.
If your ISP imposes such quality of service policies and you have no way to negotiate them with it, I propose you enforce that rules on your side too with TCP/IP stack QoS configuration.
A flush marks your TCP packet as urgent (URG flag) so that it is sent whatever the buffer/TCP window state is. Now you have to tell your operating system or any network equipment on the line to either
ignore (or simply reset) the urgent flag when the previous packet has been sent in the last 150 ms and do some buffering if necessary
delay the delivery of consecutive urgent packets to honor the 150 ms constraint.
Probably an expensive software for Windows exists to do so. Personally, I think putting a Linux box as router between your Windows workstations and modem with the appropriate QoS settings in iptables and qdisc will do the trick.
You may create a Writer wrapper implementation to keep track of last flush call timestamp. A quick implementation is to add a wait call to honor the 150 ms delay between two consecutive flushes.
public class ControlledFlushWriter extends Writer {
private long enforcedDelay = 150;
private long lastFlush = 0;
private Writer delegated;
public ControlledFlushWriter(Writer writer, long flushDelay) {
this.delegated = writer:
this.enforcedDelay = flushDelay;
}
/* simple delegation for other abstract methods... */
public void flush() {
long now = System.currentTimeMillis();
if (now < lastFlush + enforcedDelay) {
try {
Thread.sleep(lastFlush + enforcedDelay - now);
} catch (InterruptedException e) {
// probably prefer to give up flushing
// instead of risking a connection reset !
return;
}
}
lastFlush = System.currentTimeMillis();
this.delegated.flush();
}
}
It now should be enough to wrap your existing PrintWriter with this ControlledFlushWriter to work-around your ISP QoS without re-writing all your application.
After all, it sounds reasonable to prevent a connection to flag any of its packet as urgent... In such a condition, it is difficult to implement a fair QoS link sharing.

How to detect internet connectivity using java program

How to write a java program which will tell me whether I have internet access or not. I donot want to ping or create connection with some external url because if that server will be down then my program will not work. I want reliable way to detect which will tell me 100% guarantee that whether I have internet connection or not irrespective of my Operating System. I want the program for the computers who are directly connected to internet.
I have tried with the below program
URL url = new URL("http://www.xyz.com/");
URLConnection conn = url.openConnection();
conn.connect();
I want something more appropriate than this program
Thanks
Sunil Kumar Sahoo
It depends on what you mean by "internet" connection. Many computers are not connected directly to the internet, so even if you could check whether they have a network connection, it doesn't always mean they can access the internet.
The only 100% reliable way to test whether the computer can access some other server is to actually try.
Effective connectivity to the internet (i.e. where you can actually do stuff) depends on lots of things being correct, on your machine, your local net, your router, your modem, your ISP and so on. There are lots of places where a failure or misconfiguration will partly or completely block network access.
It is impossible to test all of these potential failure points with any certainty ... or even to enumerate them. (For example, you typically have no way of knowing what is happening inside your ISP's networking infrastructure.)
As #codeka says: "the only 100% reliable way to test whether the computer can access some other server is to actually try".
I think if you were to open up a HTTP session with all of:
www.google.com
www.microsoft.com
www.ibm.com
www.ford.com
and at least one of them came back with a valid response, you would have internet connectivity. Don't keep testing once you get a valid response since that would be a waste.
Feel free to expand on that list with some more mega-corporations in case you fear that all four of them may be down at the same time :-)
Of course, even that method can be tricked if someone has taken control of your DNS servers but it's probably about as reliable as you're going to get.
Just put a try/catch block around the code you mentioned. If an exception is thrown/caught then you don't have connectivity.
boolean connectivity;
try {
URL url = new URL("http://www.xyz.com/");
URLConnection conn = url.openConnection();
conn.connect();
connectivity = true;
} catch (Exception e) {
connectivity = false;
}
For better results investigate what kind of exceptions can be thrown and handle each individually.
You can check the connectivity by ask the Internet Protocol from InetAddress class. If you get an exception, or for example you use getLocalHost() -- which is returns the address of the local host -- give you the following output:
localhost/127.0.0.1 instead of fully qualified name like for example jaf-stephen-lenovoG40-80/152.6.44.13 then you're not connected to the Internet.
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.facebook.com");
System.out.println(address);
} catch (UnknownHostException e) {
System.err.println("Couldn't find www.facebook.com");
}
}
if you're connected to the Internet, you'll get the following output:
www.facebook.com/31.13.78.35
Enumaration<NetworkInterface> networkInterface = null;
networkInterface = NetworkInterface.getNetworkInterfaces();
for(NetworkInterface interface : Collections.list(networkInterface)){
System.out.println("Internet Available status is :"+ interface.isUp());
}

Categories