Open a SMTP connection - java

How to use socket to setup a SMTP server? I don't want to use any library like WISER. I just want a very simple SMTP server. How to setup?
I have tried to use the following code. But it seems like wrong.
try {
// TODO code application logic here
InetSocketAddress isa = new InetSocketAddress(25);
ServerSocket server = new ServerSocket();
server.bind(isa);
System.out.println("Server starting...");
while (true) {
System.out.println("Waiting...");
Socket client = server.accept();
if (client != null) {
System.out.println("connected");
}
}
} catch (IOException ex) {
Logger.getLogger(Fakeserver.class.getName()).log(Level.SEVERE, null, ex);
}

Related

Connect to Java socket via hostname

Is it possible to connect to Java WebSocket through flash using server hostname, not IP? The reason is the specifications of Cloud9, they don't give any IPs, only hostnames. Tests showed that WebSocket gets requests to connect through browser, but not from Socket class in Flash
programming for a Client:
Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
programming for a Server:
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
for further you can refer below URL :-
http://www.javaworld.com/article/2077322/core-java/core-java-sockets-programming-in-java-a-tutorial.html

Checking Database Server Status with Java

I want to check the online/offline status about a Database Server with Java.
Can I check this with a Socket connection over the port? I want to do this wihtout a Database connection with jdbc because the login and Database system info is unknown.
You can try the following:
try {
Socket socket = new Socket("127.0.0.1", port); //Port dependent on your DB/Server
// Server is up
socket.close();
}
catch (IOException e)
{
// Server is down
}
Yes, you can just open a Socket to the address and port of your databse server, if you get an IOException the server is down. (tested with postgress)
public boolean isDatabaseOnline(String address, int port) {
boolean result;
try {
Socket socket = new Socket(address, port);
socket.close();
result = true;
} catch (IOException e) {
result = false;
}
return result;
}
The above approaches don't really consider timing out in case the remote is unreachable, and a reasonable timeout should be defined because the default value is 20 seconds!!
You can state a timeout using the socket.connect method AFTER you create a blank socket.
SocketFactory sf = SocketFactory.getDefault();
try (Socket socket = sf.createSocket()) {
socket.connect(new InetSocketAddress(ipAdder, port), timeoutInMillis);
logger.info("database is up");
} catch (IOException e) {
logger.info("database is down");
}
The example above uses try with resources

Android Java Server Socket does not connect

I am writing an app which needs to receive a string from a server. The following code works if the IP Adress connected to is "127.0.0.1" (The Client and the server are on the same phone, just for testing purpose), but not if it is the "real" IP Adress of the phone.
Server:
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(1109);
} catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and
// accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the
// client.
os.println("Das ist ein Test immernoch");
publish("Fertig");
} catch (IOException e) {
publish("Fertig");
} catch (Exception e) {
publish("Fertig");
}
Client:
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket();
smtpSocket.connect(new InetSocketAddress("46.114.153.58", 1109), 10000); //That is the critcal line, if the IP is "127.0.0.1" everything works perfectly fine
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
return "Fehler";
} catch (IOException e) {
return "Fehler";
}
if (smtpSocket != null && os != null && is != null) {
try {
os.writeBytes("HELO\n");
String s = is.readLine();
os.close();
is.close();
smtpSocket.close();
return s;
} catch (UnknownHostException e) {
//System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
//System.err.println("IOException: " + e);
}
}
return "Fehler";
}
EDIT: Hence this is an app for a mobile device, there is no router I can configure.
Add this to your code
if (Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
You might have to forward the port you are using on your router if you are planning on using ServerSocket with external connections.
If this is the ip address of your router and you are connecting your android mobile to the router through wifi , then you have to port forward the port 1109 in your router to your mobile.
If this is the ip address of your android mobile connected through data connection , then there will be some restrictions on your data provider blocking ports for security .
46.114.153.58 is this a static ip address or dynamic ?
If its a dynamic ip address , first check the availability of the ip address by pinging it.

How to code retry policy for port in server side to listen client request?

I am writing HTTP WEB SERVER code. In the mean while I have to code retry policy on using port, so that on that port server can listen client's request.
Normal Code:
serversocket = new ServerSocket(ServerSettings.port);
It throws Exception, if ServerSettings.port is not free.
Now, I want to add retry policy, if ServerSettings.port is not free, try other ports. For that I write one code, and code is a s follows,
Updated Code:
try {
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io) {
try {
ServerSettings.port += 505;
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io1) {
try {
ServerSettings.port += 505;
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io2) {
log.info(new Date() + "Problem occurs in binding port");
}
}
}
But above one shows poor coding skills, and not professional one.
How can I write retry policy for ports in a professional way, so that server can listen on that port?
Logically, I think this will work (Correct me if there are any syntax typos):
ServerSocket serversocket;
boolean foundPort = false;
while (!foundPort)
{
try {
serversocket = new ServerSocket(ServerSettings.port); // If this fails, it will jump to the `catch` block, without executing the next line
foundPort = true;
}
catch (IOException io) {
ServerSettings.port += 505;
}
}
You could wrap it in a function, and instead of foundPort = true;, you would return the socket object.

Java SSL sockets not working

I am using TCP/IP sockets to create a client and server applicaton. Originally I was using regular sockets but now I have decided to use SSL for my connection. I have created a keystore and have tried running my application but it has yet to be successful.
Here is my code for the server
public class ArFileServer {
public static void main(String[] args)
{
boolean listening = true;
ServerSocketFactory serversocketfactory;
ServerSocket serverSocket;
try
{
//serverSocket = new ServerSocket(4445);
serversocketfactory = SSLServerSocketFactory.getDefault();
serverSocket = serversocketfactory.createServerSocket(4445);
String keystore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(keystore);
// infinite loop to continually listen for connection requests made by clients
while (listening)
{
new ClientConnection(serverSocket.accept()).start();
if (serverSocket != null)
{
System.out.println("Connection to client established");
}
}
serverSocket.close();
}
catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}
}
}
and here is the client code:
public class ClientSocket
{
SocketFactory socketfactory = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
// establish a connection to All Care's server application through socket 4444 (adjust localhost to reflect the IP address that the server
// is being run from)
public ClientSocket()
{
try
{
//clientSocket = new Socket("localhost", 4445);
//SocketFactory socketfactory = SSLSocketFactory.getDefault();
clientSocket = socketfactory.createSocket("192.168.1.8", 4445);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String truststore = System.getProperty("javax.net.ssl.trustStore");
System.out.println(truststore);
}
catch (IOException e)
{
System.out.println("Could not connect to All Care Server Application : " + e.getMessage());
}
}
}
I am also using these runtime arguments:
-Djavax.net.ssl.keyStore=C:\Users\Chris\Documents\NetBeansProjects\ArFile\keystore.jks -Djavax.net.ssl.keyStorePassword=password
When I try to print out the truststore it always returns null, what am I doing wrong?
When I try to print out the truststore it always returns null
Because you never set it. All you are doing is printing out the value of a system property. If you didn't set it, it is null.
what am I doing wrong?
Nothing yet, except printing out meaningless information. But much of your code doesn't make sense:
if (serverSocket != null)
{
System.out.println("Connection to client established");
}
serverSocket being non-null (a) is inevitable at this point, and (b) doesn't have anything do with the client socket being established, which is inevitable at this point.
catch (IOException e)
{
System.out.println("Error could not create socket connection to port, check that port is not busy");
}
An IOException at this point could mean many things, but the one thing it doesn't mean is 'cannot create socket connection to port'. It is the client that does the connecting: the server accepts connections. When you catch an exception, always print its message, don't just make up your own.
You need to define both trustStore and keyStore in runtime arguments:
-Djavax.net.ssl.keyStore=xxx.ks
-Djavax.net.ssl.keyStorePassword=yyy
-Djavax.net.ssl.trustStore=xxx.ks
-Djavax.net.ssl.trustStorePassword=yyy
Both can be same file.
trustStore contains public keys of others.
keyStore contains own keys and certificates.

Categories

Resources