Java TCP Socket Programming: Can not connect to remote host - java

I have a java program which accepts a http request from web browser and in response, program sends a text file contents to display in web browser. The program is working fine when I make request from browser which is installed on the same machine in which java code is running but when I make request from some other web browser which is not on the same machine as in which java code running, the program does not get any request.
This is how I make request from my web browser:-
http://localhost:port_number/
This is working fine...
This is how I make request from some other web browser which is not on my machine:
http://my_ip_address:port_number/
This is not working...
And this is my java code:-
while (true) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(32768);
clientSocket = serverSocket.accept();
InetAddress ia = clientSocket.getInetAddress();
jTextArea1.append("Connected to : " + ia + "\n");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine, outputLine;
String s = (String) JOptionPane.showInputDialog(this, "Enter File Name : ");
File f = new File(s);
if (f.exists()) {
out.println("http/1.1 200 ok\r");
out.println("Mime version 1.1");
out.println("Content-Type: text/html\r");
out.println("Content-Length: " + f.length() + "\r");
out.println("\r");
BufferedReader d = new BufferedReader(new FileReader(s));
String line = " ", a;
while ((a = d.readLine()) != null) {
line = line + a;
}
out.write(line);
out.flush();
jTextArea1.append("File Delivered.\n");
d.close();
}
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
jTextArea1.append("Accept failed.");
System.exit(1);
}
}

This is not related to the code that you've written. You need to make your IP address publicly accessible. Here's is a related thread.

Check that you are indeed listening on 0.0.0.0:32768 and not 127.0.0.1:32768 or any other particulat IP (specially if you are connected to several network). Start a shell and use netstat -ano on Windows and netstat -anp on Unix or Mac.
Check that your firewall allows remote connection to the port 32768

Related

Java server socket using writeBytes

I'm trying to implement a simple server using Java sockets. The server should echo back the HTTP Request message that the client sends. Thus if I enter http://localhost:8888 in to my browser, I expect to see the HTTP Request message that I sent as plain text in the web page. The code seems to do what I expect it to do, as the browser does display a http message which is the same as what is printed out in cmd when I run the program.
There are some parts of my code I wonder about though, like having:
out.writeBytes("HTTP/1.0 200 OK\r\n"); out.writeBytes("\r\n");
before my data. Is this enough to be a valid HTTP response?
Is there anything else in my code that doesn't seem to make sense, or could be improved?
Here is the full program which is executed in cmd by "java HTTPEcho 8888" for example, and checked by entering localhost:8888 in your browser, and whatever is printed in cmd should be the same as in the browser.
import java.net.*;
import java.io.*;
public class HTTPEcho {
public static void main( String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java HTTPEcho <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
try (
ServerSocket welcomeSocket = new ServerSocket(port);
Socket connectionSocket = welcomeSocket.accept();
DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
){
// echo back http request message as response to web browser client
out.writeBytes("HTTP/1.0 200 OK\r\n");
out.writeBytes("\r\n");
String s;
while ((s = in.readLine()) != null){
System.out.println(s);
out.writeBytes(s + "\r\n");
if(s.isEmpty()){
break;
}
}
out.close();
in.close();
connectionSocket.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ port + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}

PHP socket Connection refused (Java server)

I have a working Java socket, but I need some help connecting to it with PHP.
My problem: I can connect to the Java socket from a Java client and send/receive messages, but when I try to connect to the same socket with PHP, it won't connect.
This is what I have for the socket in the while loop: (keep in mind this part works)
Socket socket = serverSocket.accept();
System.out.println("Got connection");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String cmd = in.readLine();
System.out.println("Received: " + cmd);
String response = "It worked. Received: " + cmd;
out.println(response);
...
And just to show the other half that works, this is the client:
Socket socket = new Socket("<ip>", port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("test msg");
out.flush();
System.out.println("Sent message");
String r = in.readLine();
System.out.println("Response: " + r);
Now for the part that doesn't work.
This is what I am doing to try and connect with PHP:
$s = fsockopen('<ip>', $port, $errno, $errstr, 25);
if (!$s) {
echo 'Error: '.$errstr;
die;
}
Running that outputs: "Error: Connection refused"
Does anyone know how I can diagnose why the PHP can't connect but the Java client can? They are both accessing the socket externally, and since the Java client can connect it's not blocked. Is there some protocol I forgot to set?
I've looked at dozens of other people with the same question but nobody has provided an answer.
Did you look in the php.ini if fsockopen is allowed ?
1、php.ini, look for line: disable_functions = fsockopen
2、php.ini, see allow_url_fopen = On or allow_url_fopen = Off

How to find which user is using a port in Java

I'd like to map a port number to a user (linux user that is running a process that is binding to the port).
How can I do it in java?
I know I can go out to the shell and run bash commands that map a port to a PID, and then PID to user, but I'd like to keep it inside java if I can.
The more general question is: I have a webapp application that receives requests from localhost, and I'd like to know which local user performed the HttpServletRequest, so I can attach proper authorities to it.
Background:
I'm using spring security for all remote connections. However, I have a small part of the application (separated from the webapp) that is running locally alongside the application server, and that application is authenticated using the linux user mechanism. So for that reason, I bypass the server authentication rules for localhost (assuming all localhost access is permitted). The problem is with authorization - I need the identify the user running the localhost requests. Any idea how can I achieve this?
This is Linux dependent code, but not difficult to port to Windows.
This is not a Servlet code, but would work in that case as well:
Lets say I've a ServerSocket waiting on accept() call. When it receives a client request, it creates a Socket at another port to deal with that 'remote' request.
ServerSocket ss = new ServerSocket(2000);
System.out.println("Listening on local port : " + ss.getLocalPort());
while(...)
{
Socket s = ss.accept();
System.out.println("accepted client request, opened local port : " + s.getPort());
...
}
So, you need to feed the output of s.getPort() from above snippet to the following program's main() method.
public class FindUserByPort
{
public static void main(String[] args) throws Exception
{
String cmd = "netstat -anp | grep ";
int port = Integer.valueOf(args[0]);
cmd = cmd + port ;
Process pr = Runtime.getRuntime().exec(cmd);
InputStream is = pr.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
List<Integer> pIDs = new ArrayList<Integer>();
while ((line = br.readLine()) != null)
{
if (line.contains("127.0.0.1:" + port))
{
String pidPname = line.substring(line.indexOf("ESTABLISHED") + "ESTABLISHED".length());
pidPname = pidPname.trim();
String pid = pidPname.split("/")[0];
pIDs.add(Integer.valueOf(pid));
}
}
if (pIDs.size() > 0)
{
for (int pid : pIDs)
{
String command = "top -n1 -b -p " + pid ;
Process p = Runtime.getRuntime().exec(command);
InputStream _is = p.getInputStream();
BufferedReader _br = new BufferedReader(new InputStreamReader(_is));
String _line = null;
while ((_line = _br.readLine()) != null)
{
_line = _line.trim();
if(_line.startsWith(String.valueOf(pid)))
{
String[] values = _line.split(" ");
System.out.println("pid : " + pid + ", user : " + values[1]);
}
}
_is.close();
_br.close();
}
}
is.close();
br.close();
}
}

PHP/Java Sockets - Strange error?

Java code:
package servermonitor;
import java.io.*;
import java.net.*;
public class CommandListener extends Thread
{
public int count = 0;
public void run()
{
try
{
ServerSocket server = new ServerSocket(4444);
while(true)
{
System.out.println("listening");
Socket client = server.accept();
System.out.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("got reader");
String data = "";
String line;
while((line = in.readLine()) != null)
{
System.out.println("inloop");
data = data + line;
}
System.out.println("RECIEVED DATA: " + data);
in.close();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
count++;
out.write("gotcha: " + count + "\\n");
out.flush();
}
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
Java console (when I access the following PHP script):
listening
accepted
got reader
PHP code:
<?php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
When I navigate to the PHP page, it loads forever.
Any ideas?
The Java side expects a newline in its input. You're not sending one, so readLine never finishes.
Also, readLine won't return null until the socket is closed or an exception occurs (I/O error for instance). You need to return some data as soon as you've read a line if your protocol works like that.
As it was told, you need to close socket to readLine returns null.

Simple Java Chat Program Help, Client Timesout when Connecting With Server

I'm creating a very simple Java chat program, using the Java TCP sockets. I'm new to socket programming and Java. I cannot connect with server, because every time the client connects to server it times out. Maybe, it is because I'm typing the wrong IP address——I don't know.
Here is the code for the Server:
try
{
int fport = Integer.valueOf(port.getText());
ServerSocket server = new ServerSocket(fport);
Socket socket = server.accept();
msg.append("\\n Server is listening to port:" + port.getText());
BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(msgtxt.getText());
msg.append("\n\n" + input.readLine());
msg.append("\n\n" + Nombre.getText() + msgtxt.getText());
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error:" + ex.getMessage());
}
Here is the code for the Client:
try
{
int iport = Integer.valueOf(port.getText());
int i1;
int i2;
int i3;
int i4;
i1 = Integer.valueOf(ip.getText());
i2 = Integer.valueOf(ip1.getText());
i3 = Integer.valueOf(ip2.getText());
i4 = Integer.valueOf(ip3.getText());
byte[] b = new byte[] {(byte)i1, (byte)i2, (byte)i3, (byte)i4 };
InetAddress ipaddr = InetAddress.getByAddress(b);
Socket sock = new Socket(ipaddr, iport);
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
output.write(m.getText());
while(!input.ready()){}
msg.setText("\n\n" + input.readLine());
msg.setText("\n\n" + m.getText());
output.close();
input.close();
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error: " + ex.getMessage());
}
verify that you can connect to the server using telnet (on windows you may need to install it as it's not installed by default anymore).
basically, open a connection to your server and see that it works:
telnet host port
if it works, maybe the problem is not in establising the connection but in waiting for a response from the server (add the exception to your question).
one note:
you can open a socket without creating the INetAddress as you did, just new Socket(hostname, port).

Categories