I have created a simple java serversocket that listens to port 3306(in myEclipse). Then I try to connect to MySQL using toad. When I connect, the code reaches the break point that I have placed in the serversocket class. I can extract the IP and port number using: System.out.println(s.toString());//where s is the Socket.
Brief code:
ServerSocket ss = new ServerSocket(3306); Socket s = ss.accept();
System.out.println(s.toString());//Socket[addr=/192.0.0.6,port=57915,localport=3306]
What I need is the remaining details that are sent while creating connection like username and password.
How can these be extracted?
The purpose is to monitor the queries and allow only specific ones to go through.
Thanks.
Related
I am doing a project for which connection between server and client is required.
I did it by adding TCP sockets.
Here is the code fraction :
Server:
ServerSocket welcomeSocket = new ServerSocket(80);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
WorkerThread wt = new WorkerThread(connectionSocket, id);
Thread t = new Thread(wt);
t.start();
workerThreadCount++;
}
Client :
Socket skt = new Socket("192.168.0.108", 80); // The IP address is from cmd->ipconfig/all-> IPv4 Address
outToServer = new PrintWriter(skt.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(skt.getInputStream()));
It all works when both ends are in same device/under same WiFi.But I don't understand what to do for creating connection over internet.
Please help with clear steps.
Here:
Socket skt = new Socket("192.168.0.108", 80);
That is local address. If you want to have a server that is reachable on the internet, then that server needs to have its global public IP address!
In other words: you have to make sure that the server can be reached from the internet somehow. For example by turning to some service provider that hosts servers that you can then equip with your code!
The whole purpose of 192.168 addresses is to be defined only in a local subnet.
Alternatively, you have to check if your ISP has a service where the ISP assigns an IP address to your connection, and that allows calls from the internet to go to your "place".
Meaning: when you want to receive phone calls, you need a phone that is connected to the phone net!
In order to connect to a socket over WAN, you must port forward that port to your local device. This can be done in your routers' settings.
192.168.0.108 --> That's your local IP-address.
This can be used on your local network without any requirements for port forwarding whatsoever. However, to use it over WAN, execute the following steps:
Step 1: Search for your routers' model number and port forwarding on Google on how-to forward port 80 to your local IP-address. Warning: use a static IP-address on your local device to prevent your IP from changing after a reboot.
Step 2: Go to a website like IP Chicken and find your external IP-address.
You can then connect to your socket using:
Socket skt = new Socket("[EXTERNALIP]", 80);
Please be noticed: unless you have a business network, your external IP-address will probably change from time to time.
I'm stuck at a homework assignment for my university course.
We are supposed to write a game of Rock-Paper-Scissors using Client and Server, choosing TCP or UDP.
The assignment for the client part is:
"Get the IP-address and port of the server at the beginning and than use this information to connect to the server."
And server:
"The port needs to be set to a number between 10000 and 20000 at the start using command line input."
Now this got me wondering. How is the Client supposed to get the Ip-Adress and port of the server if it is not connected to the server yet?
And normally the client and the server creates a socket and the server listens if a client wants to connect and then accepts the request, making a connection, not the client, like it is requested in the assignment. Isn't it impossible to know the server, if not connected yet?
I got a version working, if the server goes:
// Setting the port via console, making an output: "please enter valid port" and returns the entered port number
ServerTest.port = ServerTest.getPort();
...
ServerSocket testSocket = new ServerSocket(ServerTest.port);
and the client:
private static String host = "localhost";
private static Integer port = 1337;
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
if I set the port to 1337 when starting the server.
Then I tried something like
//Client
port = ServerTest.getServerPort();
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
and in the server-class:
public static Integer getServerPort(){
return port;
}
But that throws an "Connection refused"-exception, even if I first the server at first, set the port and than start the client.
Does anyone have an idea how to solve this?
I'm writing a primitive Graphical MUD-like online game using only the Java standard library - just Swing and TCP sockets (for school and for fun). The game has a server (a spare laptop in my closet) that accepts TCP connections from players and takes in objects (using ObjectInputStream) - chat strings and dropped items and such - and uses those objects to make changes to the virtual world that are then forwarded to the other players.
Initially, I thought I could make each and every player connect to the same TCP port on my server (port 5010) by having my server's main thread listen for each of their connections using a loop, like so...
while (true)
{
//get new connection
serversocket = new ServerSocket(5010);
socket = serversocket.accept();
serversocket.close();
//proceed to log in player using their computer's host name.
}
Then I pass each new player's TCP socket connection to a thread dedicated to that player's object input and output, like so:
new_thread = new Thread(new Server_Input_Thread(main_thread_socket));
When I'm debugging, I test the game by running both the server side application and the client side application from my other laptop and connect through "localhost".
But I'm having problems. I can't get past IOExceptions such as Bind exceptions and "java.net.SocketException: socket closed" when listening for a new connection (on port 5010) after the initial connection (also on port 5010) has been made.
Apparently the way I'm doing it isn't working and perhaps I'll need to assign each player a unique port number rather than have every player try to connect to port 5010, or maybe it's because I'm using my coding laptop as both a client and a server.
Unfortunately for me, I have no idea what I'm doing - I just declared Computer Science as my major one semester ago. Please explain how to structure the network connections for such a virtual world and avoid the IOExceptions that occur immediately after the initial connection between the client application and the server, as the server is starting to once again listen for a new connection on port 5010 on the main thread.
Try this
serversocket = new ServerSocket(5010);
while (true)
{
socket = serversocket.accept();
//proceed to log in player using their computer's host name.
}
serversocket.close();
I am not going to show you the other problems you are going to face but this should at least get you going.
I am going through Sun's Java tutorial. I am in the lesson about sockets. There is the following code for a simple threaded server:
import java.net.*;
import java.io.*;
public class KKMultiServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new KKMultiServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
The server is said to "keep listening for more incoming connections". I just don't understand how it's possible; the line serverSocket.accept() constructs a new (client) Socket object which is, according to the tutorial "bound to the same local port and has its...". Well, how is it possible that the server is communicating with the client and listening to more incoming connections on the same port? As far as I know, if a port is used for some connection it is blocked and cannot be used for more things.
So what am I getting wrong here?
Well, a socket is not one-to-one based on a port, it is unique on a tuple of (address, port). A connection - the pair of the local and remote sockets involved in the communication - is used to demux incoming data from a port to the correct socket, allowing multiple sockets on one port. See Wikipedia. In other words, the relationship of sockets to ports are N-to-1
getting multiple connections on the same port is entirely possible as each TCP connection is a (local host, local port, remote host, remote port) tuple as long as at least 1 is different the connections are distinct and won't interfere (besides bandwidth drops)
clients attempting to connect to a server generally get a port assigned from the OS that is not used currently
Listening sockets work like a receptionist in on a business's phone switch. Everyone calls the switch number, and the receptionist responds to each incoming call on the switch line by having someone else handle the call on another line. Even though the receptionist can only take one call at a time, the switch line is tied up only very briefly because it is used only to establish a connection.
[...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1, W. Richard Stevens)
The last sentence in the above quote is the key to understanding.
Interestingly, a socket isn't really identified by the combination of IP address and port. This is unique only in context, where the context is either a particular connection or the listening state. Only one listener socket can bind to a particular IP/port combination.
The short and sweet answer is that the port is blocked for OTHER programs and processes. Only the program that opened the port can now listen on it. BUT it can listen to many different clients on the same port.
When a client connects, it creates a unique socket. A socket is comprised of the listening IP address and port (the one you opened) AND the calling IP address and port. Because the caller's IP address and port are always unique, each socket is unique and identifiable to your listener.
Even if I connected to your program twice from the same machine, my machine would select a new and random source port for each connection -- thus ensuring that we have a unique socket each time.
Based on this link
The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client.The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests.
Here is SO discussion which may clear confusion about how single port handles multiple client calls Port and Socket SO discussion .
To put it in simple terms, most of the webservers listen on port 8080 and multiple clients will access same port to access your website.
I have a Server Socket and 3-4 android devices as clients. I'm using TCP/IP for communications. Which is the best method. Should I use multiple ports for each client? Or should I use same port. If using same function then how should I identify the communication addressed to different devices?
No, you do not need several ports.
ServerSocket server = new ServerSocket(port);
while (true)
{
Socket socket = server.accept();
// do something with this socket - aka 1 client
new SomeClientClass(socket);
InputStream in = socket.getInputStream();
in.read(byte[]);
OutputStream out = socket.getOutputStream;
// out will only write response to its own client.
// when this new SomeClientClassis created, method returns to this point
// in while loop and waits for the next client
}
You can use one port. The client can send you its id. If it can't you can look at the clients IP address to workout which one it is.
There are thousands of TCP client/server code examples on the web, but I would start with the sample code which comes with the JDK,