Can we create two sockets with same portnumber - java

I am trying to create a client-server model using socket programming in Java. I have multiple clients connecting to a server socket, but once the connection is lost, I need to reconnect to the server but using the same port number for the client. I have data stored on the server with respect to the port number through which it came. Is it possible to get the same port number for a socket again?

The server has no control over which port a client connects from.
On the client side, however, a socket can be bind()'ed to a specific local IP/Port before it is then connect()'ed to the server. Just note that it may take some time for the OS to release the port from the previous connection before it can be reused again. And also, if the client has to connect through a proxy/router to reach the server, the IP the server sees will be the proxy/router's IP, not the client's IP, and there is no guarantee that the port which the server sees will be the same port which the client is using.
The real question is, why are you relying on something unreliable like a client ip/port to store your data? I would suggest using a unique ID to identify the data, like say a user login, or a server-generated ID that is given to the client. If the client disconnects and reconnect, it can just login/send back the same ID.

Related

Socket Connection Issue

I know one socket connection are established by both Server Socket and Client Socket.
And I read some documents said one Server Socket could serve many Client Sockets, means one Server Port could server multi Client Ports.
1.But I wonder that does Server use random ports to server different Clients after connection under hood, or Server just uses the same port listening and serving many client's connections ?
2.If so, when I implement a Server and Client Socket Connection, could I random a new port to establish a new Server Socket and tell Client to reconnect to new Server Socket, and the listening Server Socket just keep listening other clients ? it means use different port to server different clients ?
3.And what is the advantage of using one Server Socket(port) to server many Client? and advantage of using multi Server Sockets(ports) to server different Clients?
Thank you
The two value that idenify each end point, ip address and port number often called socket.
A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection.Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(4200);
Here u can attach your http port with socket.io.
by using a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.
for more detail visit this site

what to use for identifying between clients that connect to a server? Java, Android, Sockets

I am working with a Java desktop server and multiple Android clients connected to it. on the server side I need to identify which client has sent me a message by sockets TCP/IP and send a response only to that one client and not the others.
I will store all the sockets of clients in an ArrayList.
first here are two ways that I tried that don't work;
-- the IP address of the client, get this by calling socket.getLocalSocketAddress() in the client and socket.getRemoteSocketAddress() in the server, but they never match. for example i got in the client XXX.XXX.11.17 and in the server XXX.XXX.0.13, they are supposed to be the same for the same connection.
-- the port number, get this by calling getLocalPort() in the client and getPort() in the server, yes this works perfectly and the numbers match so I can use this, HOWEVER there is a possibility that the randomly selected port numbers on two different clients could be the same. not likely but possible. so that means there is no guarentee that they are unique.
what is the alternative that I can use that will work?
I need to identify which client has sent me a message by sockets TCP/IP and send a response only to that one client and not the others.
Send it back down the same socket you received the request from.
If you need a permanent identified for the client, you can use the result of Socket.getRemoteAddress().
getLocalSocketAddress() in the client and getRemoteSocketAddress() in the server [...] are supposed to be the same for the same connection.
No, because you don't know what's in between. Most mobile providers use proxies, NAT and so on. The mobile device thinks it's on a LAN (10.0.0.x or 192.168.x.x addresses) which the provider provides. It's even possible for multiple clients to have the same remote address (as seen from your server).
That being said, you can uniquely identify a client in your server application by the remote IP address and port combined together, given the server listens on one IP, port and protocol. This information is available from socket.getRemoteSocketAddress(), where the returned InetSocketAddress (in case of an internet socket) contains both the remote IP and port (getAddress() and getPort() respectively).
But as indicated by the other answer, you don't really need a way to identify a client. A network client is identified by the socket you receive data on (a socket is an exclusive connection between two nodes), so just send the data back to the socket that you received the request on.
If you do need more bookkeeping data about the connected client, wrap the client socket in a wrapper class that contains additional information.

Why Java ServerSocket accept() returns a socket with the same port as ServerSocket?

In the server side, i use this code :
ServerSocket server = new ServerSocket(1234);
Socket server_socket = server.accept();
I found the server is listening on port 1234.
When one or more client sockets are connected, they are all using the same port 1234 !
That is really confusing :
I remember that multi sockets can't use the same port, isn't it right ? Thanks.
A TCP connection is identified by four numbers:
client (or peer 1) IP
server (or peer 2) IP
client port
server port
A typical TCP connection is open as follows:
The client IP is given by the client's ISP or NAT.
The server IP is given by the user or looked up in a DNS.
The client chooses a port arbitrarily from the unassigned range (while avoiding duplicate quadruples)
The server port is given by the protocol or explicitly.
The port that you specify in the ServerSocket is the one the clients connect to. It's nothing more than a port number that the OS knows that belongs to your application and an object that passes the events from the OS to your application.
The ServerSocket#accept method returns a Socket. A Socket is an object that wraps a single TCP connection. That is, the client IP, the server IP, the client TCP port and the server TCP port (and some methods to pass the associated data around)
The first TCP packet that the client sends must contain the server port that your app listens on, otherwise the operating system wouldn't know what application the connection belongs to.
Further on, there is no incentive to switch the server TCP port to another number. It doesn't help the server machine OR the client machine, it needs some overhead to perform (you need to send the new and the old TCP port together), and there's additional overhead, since the server OS can no longer identify the application by a single port - it needs to associate the application with all server ports it uses (the clients still needs to do it, but a typical client has less connections than a typical server)
What you see is
two inbound connections, belonging to the server (local port:1234). Each has its own Socket in the server application.
two outbound connections, belonging to the client (remote port:1234). Each has its own Socket in the client application.
one listening connection, belonging to the server. This corresponds to the single ServerSocket that accepts connections.
Since they are loopback connections, you can see both endpoints mixed together on a single machine. You can also see two distinct client ports (52506 and 52511), both on the local side and on the remote side.

C++/Java Sockets automatic Port allocation

I've a server (Java) and a number of clients (c++), connected by sockets.
I would like to set the ports automatically.
Assuming the IP is already known.
In the Java side I can make :
ServerSocket s = new ServerSocket(0);
So now I've a random free port on the server.
How can I know in the C++ side, what port is the server listening to?
I think is not possible, if you want establish a connection with a server, you must know in which port is the server listening, there are programs like nmap that shows you a list of opened ports in a server, but a server can have many opened ports at the same time and then, How do you know what is the port opened by your server? and in any case, is too slow and inefficient to call external tool, read and parse its output. For what reason do you need a random port service?
Other option can be get the opened socket in the server side calling to s.getLocalPort() and send it via UDP for any listening node in the network with broadcasting, and re-program the client side to listen in broadcast and when it receives a message, check if it is a port number and connect to the server using that port.
You can't, not reliably. In IP, a machine is identified by an address. A server (ie, a service) is identified by an address and a port. You clients need some form of "known service" that they can connect to.
If you, for whatever reason, absolutely want to have dynamic listening port, you could combine it with a "locator" service on a known port. For instance, have a web service/servlet on the standard http port (80). Your clients connect to the "locator" service (always on port 80) and asks which port your application is currently listening on. This is a not entirely uncommon pattern. RMI works is a similar way where you have a registry on a known port. Clients connect to the registry and asks for the location of RMI endpoints.

client server interaction question

I am trying to implement a minimal chat server in java over regular TCP protocol. The chat server will listen on a specific port. The question I have is if there are multiple clients sending messages to the same port, can the server distinguish between the clients and respond to each individually if the messages do not contain the IP address or destination name of the client?
to make my question a bit more clear, suppose the server gets a packet that contains only
"user: abc to-user:efg message:"Hello""
Can I find out in java the address of the client who sent the packet and respond back to the same address or will I need to include some identifier in the message itself like "sender-ip = 1.1.1.1"
Multiple clients will never send data over the same port. The only time your clients will talk over the same port is when they will connect to the server. In the server, whenever the ServerSocket receives a connection it returns a new Socket. This socket is a combination of the following : Server IP+ServerPort and Client IP+Client Port. The Server IP and the Server Port will be same for each socket; what differs is the client IP and Port. Usually this socket is passed to a new thread for further communication while the ServerSocket goes back to listen to incoming connections. Once you have a reference to the socket you can call socket..getInetAddress().getHostAddress() to get the remote IP and socket.getPort() to get the port of the respective client.
Yes, each connection will be separate - you'll have a different stream to read from for each connection. It's up to you to associate the relevant user information with the connection though.

Categories