Why do i get the UnknownHostException if there are no proxies? - java

I am trying to test this code from oracle.com, but get the UnknownHostException. However I can easily go to oracle.com, and everything displays fine in the browser. There are no blocks or something on my computer.
Why does this happen?
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
EDIT
I appears I don't have any proxies . I checked like this
System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
List l = null;
try {
l = ProxySelector.getDefault().select(new URI("http://foo/bar"));
}
catch (URISyntaxException e) {
e.printStackTrace();
}
if (l != null) {
for (Iterator iter = l.iterator(); iter.hasNext();) {
java.net.Proxy proxy = (java.net.Proxy) iter.next();
System.out.println("proxy type: " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname: " + addr.getHostName());
System.setProperty("http.proxyHost", addr.getHostName());
System.out.println("proxy port: " + addr.getPort());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
}
}
}
the result is
detecting proxies
proxy type: DIRECT
No Proxy

Related

SMTP client for Gmail on java using sockets authentication issue

I found a socket SMTP client example slightly modified for it to connect to gmail using SSLsockets, but now I don't know how to authorise account, that I am sending from. (I don't use JAVAMAIL, because this is homework)
public class SMTP {
public static void main(String args[]) throws IOException,
UnknownHostException {
String msgFile = "file.txt";
String from = "from#gmail.com";
String to = "to#gmail.com";
String mailHost = "smtp.gmail.com";
SMTP mail = new SMTP(mailHost);
if (mail != null) {
if (mail.send(new FileReader(msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP server failed!");
}
}
System.out.println("Done.");
}
static class SMTP {
private final static int SMTP_PORT = 25;
InetAddress mailHost;
InetAddress localhost;
BufferedReader in;
PrintWriter out;
public SMTP(String host) throws UnknownHostException {
mailHost = InetAddress.getByName(host);
localhost = InetAddress.getLocalHost();
System.out.println("mailhost = " + mailHost);
System.out.println("localhost= " + localhost);
System.out.println("SMTP constructor done\n");
}
public boolean send(FileReader msgFileReader, String from, String to)
throws IOException {
SSLSocket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(InetAddress.getByName("smtp.gmail.com"), 465);
if (smtpPipe == null) {
return false;
}
inn = smtpPipe.getInputStream();
outt = smtpPipe.getOutputStream();
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return false;
}
String initialID = in.readLine();
System.out.println(initialID);
System.out.println("HELO " + localhost.getHostName());
out.println("HELO " + localhost.getHostName());
String welcome = in.readLine();
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine();
System.out.println(senderOK);
System.out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String recipientOK = in.readLine();
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
while ((line = msg.readLine()) != null) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine();
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
Rewrote the code. This works fine.
public class TotalTemp
{
private static DataOutputStream dos;
public static void main(String[] args) throws Exception
{
int delay = 1000;
String user = "xxxxx#gmail.com";
String pass = "xxxxxxxx11";
String username = Base64.encodeBase64String(user.getBytes(StandardCharsets.UTF_8));
String password = Base64.encodeBase64String(pass.getBytes(StandardCharsets.UTF_8));
SSLSocket sock = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket("smtp.gmail.com", 465);
// Socket sock = new Socket("smtp.gmail.com", 587);
final BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
(new Thread(new Runnable()
{
public void run()
{
try
{
String line;
while((line = br.readLine()) != null)
System.out.println("SERVER: "+line);
}
catch (IOException e)
{
e.printStackTrace();
}
}
})).start();
dos = new DataOutputStream(sock.getOutputStream());
send("EHLO smtp.gmail.com\r\n");
Thread.sleep(delay);
send("AUTH LOGIN\r\n");
Thread.sleep(delay);
send(username + "\r\n");
Thread.sleep(delay);
send(password + "\r\n");
Thread.sleep(delay);
send("MAIL FROM:<XXXXXXXX#gmail.com>\r\n");
//send("\r\n");
Thread.sleep(delay);
send("RCPT TO:<YYYYYYYY#gmail.com>\r\n");
Thread.sleep(delay);
send("DATA\r\n");
Thread.sleep(delay);
send("Subject: Email test\r\n");
Thread.sleep(delay);
send("Test 1 2 3\r\n");
Thread.sleep(delay);
send(".\r\n");
Thread.sleep(delay);
send("QUIT\r\n");
}
private static void send(String s) throws Exception
{
dos.writeBytes(s);
System.out.println("CLIENT: "+s);
}
}
First, Make sure you have turned on 'Allow Less Secure Apps' from your Gmail.
We can improve the code by ignoring the Multi-threading part by just reading the output from server. As we know from the RFC that server sends 9 lines after getting the first 'EHLO' request. So, we are just reading 9 lines with bufferedReader. Then for the next few commands, it returns only one line. So, the simplified code without multithreading will be like this :
import java.nio.charset.StandardCharsets;
import javax.net.ssl.*;
import java.io.*;
import java.util.Base64;
public class SMTP_Simplified_v2 {
// Credentials
public static String user = "xxxxxxx#gmail.com";
public static String pass = "xxxxxxxxxx";
private static DataOutputStream dataOutputStream;
public static BufferedReader br = null;
public static void main(String[] args) throws Exception {
int delay = 1000;
String username = Base64.getEncoder().encodeToString(user.getBytes(StandardCharsets.UTF_8));
String password = Base64.getEncoder().encodeToString(pass.getBytes(StandardCharsets.UTF_8));
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("smtp.gmail.com", 465);
br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
dataOutputStream = new DataOutputStream(sslSocket.getOutputStream());
send("EHLO smtp.gmail.com\r\n",9);
send("AUTH LOGIN\r\n",1);
send(username+"\r\n",1);
send(password+"\r\n",1);
send("MAIL FROM:<xxxxxxxx#gmail.com>\r\n",1);
send("RCPT TO:<xxxxx#gmail.com>\r\n",1);
send("DATA\r\n",1);
send("Subject: Email test\r\n",0);
send("Email Body\r\n",0);
send(".\r\n",0);
send("QUIT\r\n",1);
}
private static void send(String s, int no_of_response_line) throws Exception
{
dataOutputStream.writeBytes(s);
System.out.println("CLIENT: "+s);
Thread.sleep(1000);
// Just reading the number of lines the server will respond.
for (int i = 0; i < no_of_response_line; i++) {
System.out.println("SERVER : " +br.readLine());
}
}
}

Creating server in Java for global access

I have a problem which i've already been struggling for 3 days. I need to create server based on socket connection beetween the different local networks.
I found a lot of examples like this :
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* Created by yar 09.09.2009
*/
public class HttpServer {
public static void main(String[] args) throws Throwable {
ServerSocket ss = new ServerSocket(9999);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new SocketProcessor(s)).start();
}
}
private static class SocketProcessor implements Runnable {
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s) throws Throwable {
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello from Habrahabr</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
/*do nothing*/
}
}
System.err.println("Client processing finished");
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: YarServer/2009-09-09\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
But problem is :
i can access to this ip:port only from the same local network. If i trying to connect from the same network (from Android smartphone to local computer which has the same network ip)? so in this case all is successful, but if i trying to run the same Server sample code on, say for example AWS (Amazon Web Server)
it doesn't work :(
-> Couldn't get I/O for the connection to 172.31.23.98 (java)
or
-> org.apache.http.conn.ConnectTimeoutException: Connect to 172.31.23.98:9999 timed out (groovy)
i'm using this sample code of Server :
public static void main(String[] args) throws IOException {
int portNumber = 9998;
BufferedOutputStream bos = null;
while (true) {
try (ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
InputStream in = clientSocket.getInputStream();
BufferedReader inWrapper = new BufferedReader(new InputStreamReader(in))) {
FileOutputStream fos = new FileOutputStream(new File("D:/BufferedAudio.wav"));
bos = new BufferedOutputStream(fos);
System.out.println("Connected with client");
String inputLine, outputLine;
int bytesRead;
byte[] buffer = new byte[1024 * 1024];
while ((bytesRead = in.read(buffer)) > 0) {
bos.write(buffer, 0, bytesRead);
System.out.println(new String(buffer, Charset.defaultCharset()));
bos.flush();
out.println("Hello!!! I'm server");
}
bos.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
throw e;
}
System.out.println("Upps, the loop was unexpectedly out");
}
}
Here's the code of client :
public static void main(String[] args) throws IOException {
String IP = "172.31.23.98";
int port = 9998;
try (
Socket connectionSocket = new Socket(IP, port);
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()))
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + IP);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
IP);
System.exit(1);
}
}
These are the samples from the internet.
Amm how can i modify this code to access from Client to Server from different networks ?
The IP range 172.16.0.0 to 172.31.255.255 is a private address space for use in local area networks. IPs from that range are only valid in the same private LAN.
When you deploy your server software on a host on the Internet which is outside of your local area network, you need to replace it with the IP address of that host. I never used AWS, but the first place I would be looking for when I would want to know the public IP address of a server I rent, would be the web-based control panel. When you have shell access to the server, you can also find it out with ipconfig on Windows and ifconfig on Unix.

Cannot access web page with credentials from java

I'm accessing RabbitMQ Queue information from java code.
public class NewClass {
private static Object Base64Converter;
public static void main(String args[])
{
try {
String credentials = "test" + ":" + "test";
String encoding = base64Encode(credentials);
URL url = new URL("http://192.168.0.30:15672/api/queues");
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
private static String base64Encode(String stringToEncode)
{
return DatatypeConverter.printBase64Binary(stringToEncode.getBytes());
}
java.io.IOException: Server returned HTTP response code: 401 for URL: http://192.168.0.30:15672/api/queues
You prepare a URLConnection with proper authentication but then you don't use it when you call url.openStream(). This should work:
...
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

Java, Sockets, BufferedReader and StringBuilder

Yestarday I wrote a post about Java and Sockets, and today I'm still here because I'm having an issue with BufferedReaders.
I searched some questions here in StackOverflow and I understand the problem, but I can't fix it
My "application" has got two parts: a server and a client, and the scope of the application is to execute MS-DOS commands on the machine where the server is running (the commands are sent by the client).
Now the code (I will post the total code because it's easier to understand, I will put a comment in non-working part of the code) Server:
import java.net.*;
import java.io.*;
public class TCPCmdServer {
public int port;
public ServerSocket server;
public final String version = "Beta 1.0";
TCPCmdServer(int port) {
this.port = port;
if (!createServer())
System.out.println("Cannot start the server");
else {
System.out.println("**********************************************");
System.out.println("Command executer, server version: " + version);
System.out.println("Server running on port " + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createServer() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdServer tcp = new TCPCmdServer(5000);
while (true) {
Socket socket = null;
BufferedReader in = null;
BufferedWriter out = null;
try {
socket = tcp.server.accept();
System.out.println("A client has connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close the connection\n");
out.flush();
} catch (IOException exc) {
exc.printStackTrace();
}
if (socket != null && in != null && out != null) {
try {
String cmd = null;
while (!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder builder = new StringBuilder();
while ((line = pRead.readLine()) != null) {
builder = builder.append(line + "\n");
}
out.write(builder.toString() + "\n");
//here is sent "EnD"
out.write("EnD \n");
out.flush();
System.out.println(builder.toString());
pRead.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Closing connection...");
try {
socket.close();
in.close();
out.close();
} catch (IOException excp) {
excp.printStackTrace();
}
}
}
}
}
}
And now the code for the client part
import java.net.*;
import java.io.*;
public class TCPCmdClient {
public Socket socket;
public int port;
public String ip;
public final String version = "Beta 1.0";
TCPCmdClient(String ip, int port) {
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else {
System.out.println("**********************************************");
System.out.println("Command executer, client version: " + version);
System.out.println("Connected to " + ip + ":" + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createSocket() {
try {
socket = new Socket(ip, port);
} catch (IOException e) {
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try {
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag) {
System.out.println("Type a command... type END to close the connection");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END")) {
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else {
//The loop doesn't finish because the reader
//listens for a new line
//so I used the string "EnD", sent by the server to
//stop the loop, anyway it doesn't seem to work
//I put a comment in the server where "EnD" is sent
String output;
while (((output = in.readLine()) != null)) {
if (output.equals("EnD")) {
break;
} else {
System.out.println(output);
}
}
System.out.println(" *************************************** ");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The problem is that the BufferedReader waits for a new line forever in the while loop (I wrote a comment in the code). I tryed to stop it using a "special string", but it doesn't seem to work.
I can't change the while in
String output;
while (((output = in.readLine()) != null) && output.length > 0)
{
//code here...
}
because in the output of the MS-DOS command (think on "ipconfig") are also present empty lines.
How could I correct it?
Thank you for your help!
your client Sends "EnD " (with a whitespace at the end) and you are comparing to "EnD" without a whitespace. So the two strings are not equal. try to send it without the white space:
out.write("EnD\n");
Space is missing. In TCPCmdClient.java change
if (output.equals("EnD")) {
to
if (output.equals("EnD ")) {

Java GetInputStream Method Not Returning Back

I have Java code that tests whether a proxy is of type SOCKS or HTTP, but I noticed that when it checks if it's SOCKS the code does not return after calling the method connection.getInputStream(). What is the cause of this problem and how can I solve it?
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
public class ProxyChecker {
private final int timeout = (10 * 1000);
public synchronized void check(String ip, int port, String username, String password) {
try {
InetSocketAddress proxyAddress = new InetSocketAddress(ip, port);
URL url = new URL("http://www.my-test-url-here.com/");
List<Proxy.Type> proxyTypes = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);
for(Proxy.Type proxyType : proxyTypes) {
Proxy proxy = new Proxy(proxyType, proxyAddress);
try {
long time = System.currentTimeMillis();
URLConnection connection = url.openConnection(proxy);
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
connection.setRequestProperty("User-Agent", "My User-Agent");
if(username != null && password != null) {
String encoded = new String(Base64.encodeBase64(new String(username + ":" + password).getBytes()));
connection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
}
String line = "";
// connection.getInputStream() not returning
System.out.println("Getting InputStream...");
InputStream in = connection.getInputStream();
System.out.println("Got InputStream.");
StringBuffer lineBuffer = new StringBuffer();
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
while ((line = reader.readLine()) != null) {
lineBuffer.append(line);
}
String response = lineBuffer.toString();
System.out.println("Page: " + response);
reader.close();
in.close();
int elapse = (int)(System.currentTimeMillis() - time);
//If we get here we made a successful connection
if(proxyType == Proxy.Type.HTTP) {
System.out.println("Proxy is Type HTTP");
} else if(proxyType == Proxy.Type.SOCKS) {
System.out.println("Proxy is Type SOCKS");
}
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
ProxyChecker proxyChecker = new ProxyChecker();
//proxyChecker.check("127.0.0.1", 8080, "admin", "admin");
proxyChecker.check("127.0.0.1", 80, null, null);
}
}

Categories