How to accept connections from local network only in Java - java

I have a ServerSocket object that is listening with accept method. How do I accept connections only coming from the same network and not outside?

If your system has multiple network interfaces and one of them is receiving local connections only while others should be ignored, you can set up a ServerSocket with the IP-address of the netork interface to bind it only to that particular interface:
ServerSocket ssocket = new ServerSocket(1234, 10, InetAddress.getByAddress("192.168.1.1"));
With IPv4 and IPv6 you obviously need two ServerSockets.
If local and remote connections are received from the same network interface, you have to check the remote peer yourself. This can be done in different ways:
You can set a SecurityManager that implements checkAccept and throws a SecurityException if the connection attempts comes from the wrong place. This is a global setting, so with this you can't set up a ServerSocket at some other part of the application that should accept connections from there.
You can check the IP and port of the Socket being returned from ServerSocket to be local and close the socket if it's not instead of continuing with the request
You can create a subclass of ServerSocket overriding the method checkAccept where call super.accept, do the corresponding check as described in option 2 and only return the retrieved connection if it fit to your criterias or otherwise close it and call the super-method again.

Create the ServerSocket via the constructor that accepts a local IP address, and supply 127.0.0.1 as that IP address.

Related

SCTP INIT missing IPv4 address parameter

I have been testing the SCTP support on Java + lksctp.
I wrote a simple client in order to see just the inital setup of a SCTP association which is basically the "INIT" and "INIT ACK".
I have tested 2 ways for a Client to send the "INIT" to a SERVER which is basically:
create the SctpChannel object with "open(SocketAddress)"
try {
InetSocketAddress socketAddress = new InetSocketAddress("192.168.52.197", 2905);
SctpChannel sctpChannel = SctpChannel.open(socketAddress,1,1);
sctpChannel.bind(new InetSocketAddress("192.168.1.251",2906));
sctpChannel.connect(socketAddress, 1 ,1);
so in this way, I can see in Wireshark that I have the "IPv4 Address parameter" for all my network interfaces (3 as you can see bellow), but the Source Port is getting a aleatory port number instead the 2906 as I would like to have and it's in the bind.
So... once the bind of local IP/Port is happening after the "open"... so I have changed the code to:
create the SctpChannel object which just "open()"
binding the local client IP and Port
"connect" to the remote Server IP and Port
try {
InetSocketAddress socketAddress = new InetSocketAddress("192.168.52.197", 2905);
SctpChannel sctpChannel = SctpChannel.open();
sctpChannel.bind(new InetSocketAddress("192.168.1.251",2906));
sctpChannel.connect(socketAddress, 1 ,1);
In this way, I can see in wireshark that Source/Destination ports are expected (2906/2905), but the INIT does not have the "IPv4 Address parameter".
So does anyone know why the 2nd code I'm missing the "IPv4 address parameter" in the INIT ? Do I miss something?
Any help would be really welcome.
Thanks.
IP addresses within INIT/INIT_ACK chunks are optional parameters. In case your endpoints are signglehomed IP address might not be included in the INIT/INIT_ACK chunk. The remote end still can retrieve information about peer address from the IP header.
Fundamentally the reason of this behaviour is what parameters you pass to open(). Open() without any parameters and open() with remote address specified works in a different way.
If you call SctpChannel.open(socketAddress,1,1) with socket address for the remote end it effectively open channel and connects to remote end (see open documentation. Your bind() and connect() calls in this case are pretty useless. So since there were no bind() call prior to establishing the connection you are sort of using "default" endpoint with random port (56044) and IP addresses of all available interfaces.
In second case, when you don't specify socketAddress for open() it just open the channel but does not connect to remote end at this stage. So your bind() call successfully specify endpoint details (port and IP address) and when you call connect() it is actually using the endpoint you just created (192.168.1.251:2906) to setup connection with remote end.

Difference between Socket & InetSocketAddress?

I searched a lot but I was not able to find a direct difference between the two. When do we use each one when it comes to creating a client socket?
An InetSocketAddress does not manage a Socket in any way.
I think you mean Socket vs DatagramSocket.
Socket is for connections communicating via TCP (reliable).
DatagramSocket is for connections communicating via UDP (unreliable).
Or, if you're referring to SocketAddress vs InetSocketAddress:
SocketAddress is simply the abstract implementation of a Socket Address with no protocol.
InetSocketAddress is an implmentation of SocketAddress, for IP.
It is all in the name... A typical network socket is a connection between two ports on two machines.
The ServerSocket is the one that waits for clients to connect to it.... it 'binds' to a port, and it 'Listens' for connections, and when they happen, it 'accepts' the connection. The result of the accepted connection is a Java Socket. The client that connected (if it is also Java), also has a Java Socket. You now have two sockets connected to each other.
The Socket is described above.
Now, the address is the details about how to find/identify the remote side of the Socket connection.
A SocketAddress is the abstract class for something that can tell Java where to connect to when contacting a server, and it allows the Sockets to identify remote servers/clients once the connection is made.
An InetSocketAddress is a special SocketAddress designed to represent the standard TCP Protocol address, so it thus has methods to set/query the host name, IP address, and Socket of the remote side of the connection (or, in fact the local side too).
So, the (Inet)Socket address is used to establish Socket connections...
Summary:
ServerSocket is a listener that waits for socket connections to be established.
Socket is the communication channel between two systems (one the server, the other the client).
SocketAddress is an abstract class that identifies an address
InetSocketAddress is a class that is specific for the TCP protocol consisting of IP Addresses/host-names, and port numbers. This is used to establish internet/TCPIP sockets.
Reference taken from
https://softwareengineering.stackexchange.com/questions/231150/whats-the-difference-between-socketaddress-and-serversocket-in-java
From the Javadoc for Socket
This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.
and for InetSocketAddress
This class implements an IP Socket Address (IP address + port number)
The address is like the location of your house, the Socket is the road which leads to that house.
A SocketAddress is the abstract class for something that can tell Java where to connect to when contacting a server, and it allows the Sockets to identify remote servers/clients once the connection is made.
An InetSocketAddress is a special SocketAddress designed to represent the standard TCP Protocol address, so it thus has methods to set/query the host name, IP address, and Socket of the remote side of the connection (or, in fact the local side too).

Get domain name of incoming connection

I don't find any information on this topic on the internet and asked here. For example I have server with IP 1.1.1.1 and 2.2.2.2 and two domain names pointing to it one.example.com and example2.net, and socke listening on port 1234 for incoming connections.
For example:
C/C++:
listenfd=socket(AF_INET, SOCK_STREAM, 0);
bind(...);
listen(...);
while(...) accept(...);
or Java:
ServerSocket socket = new ServerSocket(1234);
while(...) {
Socket connectionSocket = welcomeSocket.accept();
...
}
When client accepted on my socket I need to know what domain name/IP is used by the client to connect. It may be one.example.com or example2.net and/or IP 1.1.1.1 or 2.2.2.2 (if connected using IP only).
Apache somehow determined ip/domain of incoming reques, and I need to do such thing in pure socket code. C++ (main) or Java (or any other) accepted, I need to know mechaniics of this.
The IP is stored inside the IP packet header and you can read it from there. In order to get the host, you'll probably have to ask a DNS server by sending a request (or use a function which does it for you). You can find examples for both of the problems, even on this site

What's happening when server.accept()

I'm trying to write a simple Java chat application in Server/Client.
I'm confusing in below method at server.accept() :
private void waitForConnection() throws IOException {
showMessage("Waiting for someone to connect... \n");
// `connection` is an instance of `java.net.Socket`
// `server` is an instance of `java.net.ServerSocket`
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
Please tell me connection is equal to what?
And also server.accept() returns what?
Any helps would be awesome.
Assuming your server variable is a java.net.ServerSocket then the accept() method returns a java.net.Socket object.
From the returned Socket object, you have access to both the InputStream and OutputStream to read from and write to the connected client.
Your program should halt until a client connects. That's what the line connection = server.accept(); does. Returning type is a type of Socket, too.
That's the "connection" to your client, you can read from and write to.
Check this and that site to read more about network programming in Java.
when you do connections between two systems then you require a socket.
Socket of one system is connected with socket of another system. Both these sockets are connected via I/O stream. you can write to this stream and can read from this stream.
One system serves as server and another system serves as client .
As socket is combination of port no. and IP so server open its port no. and client try to connect with the server's IP and port no.
For connection to be maid the server accepts the incoming socket using accept() function. accept() function returns a local socket which is connected to another socket at the client..
accept() waits until a client socket arrives.

MulticastSocket: Socket operation on non socket

I have some code like this:
InetAddress bind = InetAddress.getByName("192.168.0.1")
MulticastSocket socket = new MulticastSocket(new InetSocketAddress(bind,0));
socket.setInterface(bind);
On windows 7 and windows XP with JDK6u17,I got a SocketException: Socket operation on non socket.
But if I change the line 2 to :
MulticastSocket socket = new MulticastSocket(0);
It's ok, and works find too with jdk6u14.
Why? thanks.
EDIT:
Why port 0 should be the matter?
MulticastSocket socket = new MulticastSocket(0);
Everything goes well with this code.But not
MulticastSocket socket = new MulticastSocket(new InetSocketAddress(bind,port));
Whatever the port is.
As you are binding to a specific interface, calling setInterface() to the same interface is redundant. Remove it. It's only needed when you bind to INADDR_ANY, or in Java an InetAddress of null (or unspecified as a parameter).
To address errors in some of the other answers, and their implications:
Port zero is legal. It means a system-assigned port.
You only need a MulticastSocket for receiving multicasts. For sending, you can just use a DatagramSocket.
If the multicast interface needs to be specified, which it doesn't in this case, it can be done either via MulticastSocket.setInterface() or when calling joinGroup() or leaveGroup(). The latter option gives you granularity at the group level, but both techniques work. That's why they're both provided.
If you don't bind to a specific interface you should definitely call setInterface(). If you are on a multi-homed host you must to call joinGroup()/leaveGroup() once per interface, if you want to receive via all of them.
And a question: is 192.168.0.1 an IP address of an NIC on the local machine? It needs to be.
According to the documentation, you are supposed to instantiate it with a port number (thus 0 would be valid).
I am not so sure.
What's the constructor MulticastSocket(SocketAddress bindaddr) for.
And why it works fine with jdk6u14,but not jdk6u17?
And why it ok on windows 2003 server with jdk6u17?
On RHEL5.2 jdk1.4+
http://www.sockets.com/err_lst1.htm
Berkeley description: An operation was attempted on something that is not a socket. The specified socket parameter refers to a file, not a socket.
WinSock description: Same as Berkeley. The socket input parameter is not a valid socket handle (either it never was valid, it's a file handle (not a socket handle), or if it was a socket handle, it has been closed).
Detailed description:
select(): fails with WSAENOTSOCK if any socket in an fd_set is an invalid socket handle.
Developer suggestions: Did you close a socket inadvertently in one part of an application without keeping another part notified? Use socket state in an application and/or handle this error gracefully as a non-fatal error.
when the MulticastSocket created,socket.isClosed()==true
I haven't used these classes before, but the Exception occurs on line 3 when you call the setInterface method.
I would guess it's something to the effect that you're using the same reference twice or something.
I found a snippet of code that looked like this, maybe this is how you should be doing it:
MulticastSocket ms = new MulticastSocket(new InetSocketAddress(0));
ms.setInterface(InetAddress.getByName("192.168.0.1"));
You should first create the Multicast socket with a well known port - something higher than 1024 and less than 65535 - as already stated 0 means the operating system will choose a port for you (but then its going to be kinda random - which I guess you don't want).
For multicast - you generally need to set the interface to use on joinGroup() not on creation - e.g:
MulticastSocket socket = new MulticastSocket(2121);
InetSocketAddress socketAddress = new InetSocketAddress("localhost", 2121);
if (networkInterfaceName != null){
NetworkInterface ni = NetworkInterface.getByName(networkInterfaceName);
socket.joinGroup(this.socketAddress, ni);
}else {
socket.joinGroup(socketAddress.getAddress());
}
According to the MulticastSocket documentation you should use
Class D IP addresses in the range
224.0.0.0 to 239.255.255.255, inclusive
to bind a MulticastSocket. Apparently, the "192.168.0.1" is out of the multicast range.

Categories