TCP socket connection over internet - java

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.

Related

ServerSocket MySql connectivity

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.

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.

Client-Server application on different computers

I want to modify my code to make the clients connect to the server if the server is hosted on a different machine. This is the code I have now:
Server:
int port = 5000;
ServerSocket server = new ServerSocket(port);
Socket socket = server.accept();
output/input streams....
Client:
String host = "localhost";
int port = 5000;
Socket socket = new Socket(host, port);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
I am aware of the inetAddress and that's what I need help with, I don't know how to use it correctly, I don't want any complicated methods just enough to connect them together. Also I want to know if it is possible to use DNS for this or if I need a web server or something similar (of course DNS is purely curiosity).
To connect to a remote machine you need that machines IP address or hostname, then you can use InetAddress.getByName(String).
You'd use the IP address if there's no DNS server available to resolve the IP from the hostname, like this:
Socket socket = new Socket(InetAddress.getByName("1.2.3.4"), 5000);
Or is there's is a DNS server, then you can just pass the servers hostname like this:
Socket socket = new Socket(InetAddress.getByName("myserver"), 5000);

Accept all incoming requests on a ServerSocket

I'm temporarily using the following line to create a ServerSocket on my Android phone:
socketl = new ServerSocket(port, 0, InetAddress.getByName("192.168.0.108"));
But it's really annoying and, besides, not user-friendly to change the IP address manually every time the DHCP assigns a new IP to the phone. So I'm searching for a way to get the IP-Address the DHCP-Server gave to my phone.
Ive tries InetAddress.getLocalHost().getHostAddress(), but that only returned the IPv4 loopback (127.0.0.1).
Is there a way to either get the current local IP(v4) or a way to accept every request, no matter which IP is used to connected? If the IP-Address in the line above isn't the same as the one the client uses, it doesn't work.
You could use
socketl = new ServerSocket(port, 0);
or even
socketl = new ServerSocket(port);

Android app won't connect to computer that's connected wirelessly to network

The app uses sockets to connect to the computer but will only connect if the computer is connected to the network by an ethernet cable. I've tried disabling the firewalls but that makes no difference.
The code for the server on the computer:
int port = 7936;
while(true){
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client ...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected");
InputStream in = client.getInputStream();
and the code for the client on the app:
Socket socket = new Socket(address,7936);
OutputStream out = socket.getOutputStream();
String action = "2";
byte[] actByte = action.getBytes();
out.write(actByte);
socket.close();
Address is defined by user input and all the permissions needed have been set in the manifest xml file.
Thanks for the help.
Edit
Sorry for the delay in responding to the answers given. I have since been able to try the program on a different network and it works with the computer connected wirelessly so it looks like the issue was with the network rather than the code.
Thanks to everyone for answering and I'm sorry it took me so long to respond.
As others have mentioned, more information is needed. When you disconnect the computer from the wired connection, I assume it is switching over to wifi and you've verified that you are online. Your computer is likely to get a different IP address if you're DHCP as the interface changed and so wouldn't the MAC address.
Check the address on the computer and verify you have the right address.
What I'm thinking is that the socket is not bound to the IP address you think it is. You may wish to try using the TcpListener class, that way you can bind it to the IP address (network adapter) you want.

Categories

Resources