Socket programming client name - java

Is there any way to get client name at the server side before "accepting" the connection? Using java.
I am new to java.
thanks in advance..

Is there any way to get client name at the server side before "accepting" the connection?
No - you must accept the connection first. Then you may read the host's name and choose the next course of action.
Socket client = server.accept();
String hostName = client.getInetAddress().getHostName();

The client name (the client hostname) is avalaible only from the Socket client, so you need to accept it first and then then to react accordingly.
private static final String ALLOWED_NAME = "my.hostname.com";
....
Socket client = server.accept();
String hostName = client.getInetAddress().getCanonicalHostName();
if(hostName.equalsIgnoreCase(ALLOWED_NAME)
{
// DO NOTHING
}
else
{
client.close();
}
Reference:
Socket
InetAddress
Please be sure to get the difference between getCanonicalHostname() and getHostname().

Related

Setting source port on udp socket

We've developed a Java application that sends several UDP datagrams to the very same destination IP address. Obviously the destination port is always the same one, but we can't seem to be able to set the source port to remain the same on each datagram.
If the data package we send is bigger than MTU the package is properly splitted over the same source port, but once we send a new data package the source port changes, generating a new firewall session (which network admin has warned us to be very bad due to the amount of sessions the application is generating).
Right now we're sending the packages with the following statement:
We've tried several approaches and the result is always the same, we can't seem to be able to set the source port to a fixed value.
Edit- pasting actual code:
private boolean sendImage(byte[] imageData, InetAddress address,
int port) throws UnknownHostException, SocketException {
boolean ret = false;
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
DatagramPacket dp = new DatagramPacket(imageData, imageData.length, address, PUERTO_UDP);
socket.send(dp);
ret = true;
} catch (IOException e) {
Main.lanzarExcepcion(e);
ret = false;
} finally {
if (socket != null) {
socket.close();
}
}
return ret;
}
Thanks for your time!
I think your issue is that you are closing the actual DatagramSocket instead of reusing the same , and simply call socket.send(DatagramPacket). If you cant keep the client socket open , then you could even define the clients port like : DatagramSocket clientSocket = new DatagramSocket(9743); so each time you are calling a new clientSocket , it will get the same port or it will throw a java.net.BindException: Address already in use: Cannot bind
This will not solve the network sessions issue, because you are opening a new UDP Socket. Also i suspect that your network admin , sees the previous sessions , because you are not closing the UDP Sockets at all , but simply spawning them
As mentioned by #AntJavaDev
The solution was to:
1.- keep the DatagramSocket open
2.- pass src port in the arguments
3.- reusing the unclosed DatagramSocket for every new data packet to the same destination!
Thanks all!
The source port is an ephemeral port, generated for you by the underlying networking implementation. There is no reason to set it to a particular port number.

Java sockets: Client get IP-adress and port to connect to server

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?

ID for local client using sockets in java

I want get unique ID for my client connected by a server. I have many clients, but, each one want has one different ID. An close solution is similar to this:
Socket cliente = servidor.accept();
System.out.println("New connection with" +
cliente.getInetAddress().getHostAddress());
String addr = servidor.getLocalSocketAddress().toString();
ThreadServidor ts = new ThreadServidor(addr, cliente);
ts.start();
The clients have the same code to connect:
Socket conexao = new Socket("127.0.0.1", 12345);
I need the information of the own client ip and port connected too.
Thanks
The following methods can be called on your socket cliente to get the local and remote IP addresses and the local and remote ports.
getLocalAddress()
getLocalPort()
getInetAddress() // gets the remote address
getPort() // gets the remote port
The combination of all that information is unique.
More info at the Javadoc:
http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
Just use Socket.getRemoteSocketAddress(). It embodies the remote host:port, which is all you need at the server end.

Chat using TCP in Java

I am making a chat in Java which uses a TCP protocol.
I have a client and a server side.
To send a message to another user, I have to send the message to the server through my client, and the server has to send it to another client.
The server holds the addresses of both online users. When I send a private message, the server finds the ip and a port and creates a socket from them.
The problem is that it doesn’t work correctly.
Here’s the code:
int portNumber = 4444;
String host = "192.168.0.100”;
Socket link;
try {
link = new Socket(host, portNumber);
// Then I set to already created PrintWriter the outputstream
out = new PrintWriter(link.getOutputStream(), true);
} catch (Exception e) {}
// Unfortunately the server freezes here (it doesn't show anything).
How to solve this problem? Where dod I make a mistake?
Thank you in advance.
You shouldn't create a new Socket to send a message. Instead, use a socket of an existing connection.
The sequence should be the following:
Client A connects to the server (server stores the connection as SocketA).
Client B connects to the server (server stores the connection as SocketB).
Server reads a private message from SocketA. The message is addressed to client B.
Server finds the existing socket for client B. It's SocketB.
Server sends the message into SocketB.

Communiation with multiple clients via Sockets

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,

Categories

Resources