Binding Socket to any existing address on specific subnet - java

I have a java application in which I want to receive a udp broadcast telegram in a known subnet, for example 192.168.x.x (255.255.0.0). If I know the IP of the machine which is running the application, the following works (assuming the IP of the machine is 192.168.10.1)
InetAddress ip = InetAddress.getByName("192.168.10.1");
DatagramSocket socket = new DatagramSocket(2222, ip);
But if the IP is not fix, maybe from a dhcp server, how could I create a socket which is bounded to the ip which the machine gets from the dhcp server. There may be other interfaces on other subnets, so if I will use
DatagramSocket socket = new DatagramSocket(2222);
the socket is not surely bounded to the ip in the subnet with 192.168.x.x.
How could I solve this?

So if I understand your problem is to get the address assigned to an interface. I suppose you have more than one interface and you want to select one.
Also note by using DatagramSocket socket = new DatagramSocket(2222); you are binding to the wildcard address that often mean any and should work in many cases
From Oracle documentation List Network interfaces you can retrieve inetAddress from different interfaces
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}

Related

UDP Chat Program different networks can't chat

I'm trying to make a chat program where the client and the server can chat with each other on different networks (not localhost) I'm currently faced with a problem that i don't know how to solve.
For some reason, the client and the server can't connect to each other, when i write a message to the server with the client, nothing pops up on the server. The tests were run on two different computers, on different networks (Mobile data and Ethernet)
I've used the public ip from my ethernet in the code, and portforwarded it with the matching port number in the code. The server is running on the portforwarded network.
This is my code:
CLIENT:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
DatagramSocket client = new DatagramSocket(7000);
byte[] receivedData = new byte[1024];
byte[] sentData;
InetAddress address = InetAddress.getByName(" PUBLIC IP IS HERE, won't show it for obvious reasons ");
while (true) {
String message = scanner.nextLine();
sentData = message.getBytes();
DatagramPacket dp1 = new DatagramPacket(sentData, sentData.length, address, 7000);
client.send(dp1);
DatagramPacket dp4 = new DatagramPacket(receivedData, receivedData.length);
client.receive(dp4);
String receivedMessage = new String(dp4.getData());
System.out.println(receivedMessage);
}
}
}
SERVER:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatServer {
public static void main(String[] args) throws IOException {
DatagramSocket server = new DatagramSocket();
Scanner scanner = new Scanner(System.in);
byte[] receivedData = new byte[1024];
byte[] sentData;
while (true) {
DatagramPacket dp2 = new DatagramPacket(receivedData, receivedData.length);
server.receive(dp2);
String storedData = new String(dp2.getData());
System.out.println(storedData);
InetAddress getIP = dp2.getAddress();
int port = dp2.getPort();
String sentMessage = scanner.nextLine();
sentData = sentMessage.getBytes();
DatagramPacket dp3 = new DatagramPacket(sentData, sentData.length, getIP, port);
server.send(dp3);
}
}
}
The code worked when altered to localhost only.
Does anyone know what i'm doing wrong? Any replies are greatly appreciated.
Assuming the client connects to the server, the server needs to specify the port to listen and the client needs to specify IP and port of the server.
Client:
InetAddress address = InetAddress.getByName(" PUBLIC IP IS HERE");
DatagramSocket client = new DatagramSocket();
//...
DatagramPacket dp1 = new DatagramPacket(sentData, sentData.length, address, 7000);//the port should be the publicly exposed port
client.send(dp1);
This connects to the server with specified IP and port.
Server:
DatagramSocket server = new DatagramSocket(7000);//port to forward
This means that the server listens on port 7000 so it is available under that port.
Aside from that, make sure the port forwarding works correctly. If you use UDP, you also need to configure it for TCP.
Also note that UDP does neither confirm nor validate packages. If you want to have those features, you will need to either use TCP or implement those features by yourself.

Why I can't connect my sockets from two PCs in Java?

So far I have achieved making server/client relations on the same computer by parallelly running different java classes. As I don't want to overcomplicate this question, I will post my simplified code which works perfectly fine.
Server:
public class Server {
public static final int PORT = 9090;
public static void main (String[] args) {
try {
ServerSocket serverSocket = new ServerSocket (PORT);
Socket client = serverSocket.accept ();
System.out.println ("Client connected!");
} catch (IOException ioException) {
ioException.printStackTrace ();
}
}
}
Client:
public class Client {
public static final int PORT = 9090;
public static final String IP_ADDRESS = "127.0.0.1";
public static void main (String[] args) {
try {
Socket socket = new Socket (IP_ADDRESS,PORT);
} catch (IOException ioException) {
ioException.printStackTrace ();
}
}
}
After I run them, I get the expected output - console in class Server prints "Client connected!".
Like any other curious programmer, I decided to try out the same program on my two laptops. One laptop has client code, while second has server code. Of course, I had to change "127.0.0.1" or "localhost" to ip address my server laptop has by typing on google "what is my IP address". I just copied that new IP address into IP_ADDRESS variable and hoped it would work the same. Unfortunately, it didn't happen. My client laptop looks as if it never connected to server laptop, because server laptop never printed message "Client connected!". What am I missing? It looks so easy, yet it doesn't work. Could someone help me solve this?
P.S. I don't want to share my IP address due to privacy reasons, but it was the first number that pops when any of you google: what is my IP address?
If you are on a local network, you don't have to take your public IP. You need to find your local IP (if you are on linux, a simple "ip a" and you'll have your IP address, if you are on windows )
If you are not on a local network, you could open your router' settings to open the 9090 port but I STRONGLY discourage you to do something like that for security reason.

Multicast Socket Joined Client Ip Address

I'm working in client server project in java. i'm using MulticastSocket . I have to send some message to selective clients. But i don't know how to get joined client address. Can anyone please help me out.
Use code like below, this may help you.
private void init() throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.configureBlocking(true); //optional
channel.bind(new InetSocketAddress(5000));
InetAddress iGroup = InetAddress.getByName("224.0.0.1");
NetworkInterface intrf = NetworkInterface.getByName("lo"); // lo name could be changed according your requirement
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, intrf);
channel.join(iGroup, intrf);
}

Java doesn't recognize Wi-Fi Broadcast address

Alright, so I adapted the code from http://enigma2eureka.blogspot.com/2009/08/finding-your-ip-v4-broadcast-address.html in an attempt to find the IP address of the Broadcast Address on my Wi-Fi Router.
protected static InetAddress getBroadcastAddress() throws SocketException {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
System.out.println(networkInterface.toString() + networkInterface.getInterfaceAddresses());
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback interface
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null)
continue;
return broadcast;
}
}
return null;
}
However, it prints the following - the name and the list of interface addresses:
name:lo (Software Loopback Interface 1)[/127.0.0.1/8 [/127.255.255.255]]
name:eth0 (Microsoft Kernel Debug Network Adapter)[]
name:net0 (Belkin USB Wireless Adaptor)[null]
...
The Belkin adapter - net0 - seems to have a null broadcast address, although it shouldn't. (I did remember to set the prefer IPv4 system property) Can anyone identify why it returns null?

How to get IP address via java or javascript?

My computer name is D*******.
When it is not connected to VPN client it gives same ip address from ipconfig and www.jsonip.com too.
But when I connect to VPN client the ip4 address changes to ppp adapter ip address, whereas the www.jsonip.com site still retrieves Ethernet ip4 address.
Is there a javascript or java way to get ip address via resolving the Computer Name?
JAVA check this..
import java.net.InetAddress;
public class GetIPAddress {
public static void main(String[] args) {
try {
InetAddress thisIp = InetAddress.getLocalHost();
System.out.println("IP:" + thisIp.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Another JAVA sample Code
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("google.com");
System.out.println(Address);
For JS Try this javaScript code it might help you.
Superuser
http://jsfiddle.net/
Try this.
import java.net.InetAddress;
class IPAddress
{
public static void main(String args[]) throws Exception
{
System.out.println(InetAddress.getLocalHost());
}
}

Categories