My problem is: I need to discovery if one IP and Port is running a SMTP service.
To do this, I'm using SMTPClient to try open a connection. I'm using the code below.
private static boolean validateSMTP(String ip, int port, int timeOut) {
SMTPClient smtp = new SMTPClient();
try {
smtp.setConnectTimeout(timeOut);
smtp.connect(ip, port);
return true;
} catch (SocketException e) {
LogAplication.Warning("Ops... something wrong", e);
} catch (IOException e) {
LogAplication.Warning("Ops... something wrong", e);
}
finally{
smtp = null;
}
return false;
}
It's working fine and I've gotten the expected results, but the timeOut has been my problem.
E.g: If I try ip: 127.0.0.1 and port 80 (IIS open port) the connect step takes a long (much more than is defined in timeout) to throw an exception
java.net.SocketException: Connection reset
How can I set timeOut for this case? Or existis another way to do my simple test ?
After take a look at grepCode, I found this for method connect(string host, int port):
Opens a Socket connected to a remote host at the specified port and
originating from the specified local address and port. Before
returning, _connect Action() is called to perform connection
initialization actions.
As the port is opened by another service, the socket is opened, not causing timeOut (by socket), but the exception was thrown by "connectAction()"
So I needed to set a global timeOut for my SMTPClient, which is used by socket connection and inside of "connectAction()" . And I did this to solve my problem:
smtp.setDefaultTimeout(timeOut);
With this, now I've the expected results for, open ports which throws exceptions and of course, the successfully connection for SMTP services.
Related
I'm trying to create a local server with Wi-Fi P2P between an Android phone and a Raspberry Pi, with the Android as the host. I have been able to successfully establish a P2P connection using wpa_cli on the Pi, but now I am trying to use a C client socket to connect to the phone and transfer data. However, the line Log.d("Socket waiting", serverSocket.getLocalSocketAddress().toString()); spits out D/Socket waiting: ::/:::8888. It doesn't seem to have an address at all, so how am I supposed to connect to it?
As indicated by my comment, my research told me that the correct IP should be 192.168.49.1. If the IP were any different, that would be okay, because I can just send a BLE packet to the phone, telling it the IP. My issue is that the IP is entirely blank.
My code is as follows, for a thread that waits on a connection:
public static class DataTransfer extends Thread {
#Override
public void run() {
Log.d("DataTransfer", "Start");
ServerSocket serverSocket = null;
try {
/**
* Create a server socket and wait for client connections. This
* call blocks until a connection is accepted from a client
*/
// Expects a connection at 192.168.49.1:8888
serverSocket = new ServerSocket(8888);
//serverSocket.setReuseAddress(true);
//serverSocket.toString()
Log.d("Socket waiting", serverSocket.getLocalSocketAddress().toString());
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
Log.d("InputStream Available", String.valueOf(inputstream.available()));
serverSocket.close();
}
catch (IOException e) {
Log.e("Receive Error", e.getMessage());
if(serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
Log.e("Failed to close socket", ex.getMessage());
}
}
return;
}
}
}
And here is the output of ip a on the Pi, once it is connected via Wi-Fi P2P
11: p2p-wlan0-8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether b2:0e:07:e6:e6:55 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.23/24 brd 192.168.1.255 scope global noprefixroute p2p-wlan0-8
valid_lft forever preferred_lft forever
inet6 fe80::e79c:33f3:6e49:b6ed/64 scope link
valid_lft forever preferred_lft forever
Final edit:
My problem was seemingly unrelated. As both comments below indicate, the IP shown off is fine, it just means it accepts connections from anything. My actual issue was that I had a static IP set up on my Pi without specifying which interface the static IP was for. The client needed to be on a 192.168.49.# address, and the static IP was preventing it.
You can specify the interface the server socket is listening on by passing an address to the constructor:
serverSocket = new ServerSocket(8888, 10, InetAddress.getByName("192.168.49.1"));
Seeing :: means your server was listening for IPv6 connections on all interfaces. That is represented by the IPv6 address of all zeros which can be written as ::. But you are trying to connect to an IPv4 address, not IPv6. Most systems I've worked with are configured so that IPv4 connections can be accepted by an IPv6 server, but I guess yours isn't. The answer to this question suggests you may be able to change your system's behavior with sysctl:
sysctl net.ipv6.bindv6only=0
:: is the IPv6 default route. It indicates that you are serving requests from all interfaces.
This is the expected behavior. Is there a problem with that?
Good day,
I have a java game that I want to play with a friend over network, I have implemented Sockets and tested the game on my pc using localhost as address, but was unable to connect to the external ip of my pal's pc, presumably due to us both being behind routers.
Here is the code of host/client:
CLIENT:
try {
socket = new Socket(inputHostIp(), 5555);
} catch (IOException e) {
e.printStackTrace();
}
SERVER:
try {
hostServer = new ServerSocket(5555);
} catch (IOException e1) {
e1.printStackTrace();
}
listenForUserConnection();
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
Socket socket = null;
try {
socket = hostServer.accept();
} catch (IOException e) {
e.printStackTrace();
continue;
}
joined(socket);
}
The exception I am getting now is
java.net.ConnectException: Connection timed out: connect
On trying to init I/O:
java.net.SocketException: Socket is not connected
java.net.Socket.getInputStream/java.net.Socket.getOutputStream
I have set up port forwarding with the chosen port number (5555) linked to the internal ip on both our machines.
What are my options for getting this to work?
ADDENDUM:
We have also tried using Hamachi to create a virtual LAN, but there seems to be an issue with that - we can’t ping one another even through that, it diagnoses with an issue -
Tunnel:
VPN domain's tap device is down
Local results:
Adapter configuration:
Cannot get adapter config
Traffic test: Cannot complete test
Peer results: [160-056-951]
Adapter configuration: OK
Traffic test: Inbound traffic blocked, check firewall settings
I have tried shutting down firewalls, hamachi issues changed to just ‘cannot get adapter config’, but otherwise no results.
On my pc, however, I got a version of windows that doesn’t seem to display Firewall setting properly, if you think it’s likely an issue, can you tip me on how to test my firewall?
I am using Java to do the socket programming as below.
Client program is as below:
Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Server program is as below:
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Socket clientSocket = null;
try {
clientSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
Now my question is if I run more than one thread to open several sockets in one port (as the server code above), how my client program know which socket it is connecting to?
Your client connects to the Servers port. So all clients will be having the same code
MyClient = new Socket("Machine name", <port where server is listening>);The port opened at client side is not important. The client will get a free port available in his OS.
how my client program know which socket it is connecting to?
The question doesn't make sense. It doesn't 'connect to a socket' at all, it connects to a listening port, and there is only one of those. Your server only accepts one client, so the second and subsequent threads will get an undefined behaviour ranging from a ConnectException to a ConnectionException to nothing, most probably the latter.
Your application knows it because you set it up with a specific port. There is no "auto discovery" built into TCP/IP, it's up to you to pick a server-port and make sure you set your clients up to connect to that port. Either you hard-code this into your client application or, better yet, have it in some configuration file you include with the client.
This is why you have a bunch of "known ports", like http is port 80. This means that a browser will always connect to port 80 on a web-server, unless you explicitly indicate another port in the URL.
I'm getting following error when my client tries to connect to my server socket:
java.net.ConnectException: Connection refused: connect
But, my server is really running, on the same machine. I try to connect to it by using the external IP of my router. But when I try to connect with "localhost", it works. And, yes I did port forwarding correcly in my router. Even canyouseeme.org can connect to my server (The site says: "success" and in my server-log appears that someone connected with the server.)
So, is it for one or another reason impossible to connect to the same machine (or to a machine in the same network) via an external IP? Or is this something typical for Windows? (Normally, I use Linux)
I also tried to completely disable Windows Firewall.
ServerSocket:
public ServerSocket ssocket;
public List<ClientHandler> handlers;
public Server(int port) { // Constructor
try {
ssocket = new ServerSocket(port);
this.handlers = new ArrayList<ClientHandler>();
IpSharingManager.uploadData(Utilities.getPublicIp(), port);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
Client:
public InvisibleClient(String host, int port) {
try {
System.out.println("Trying to connect to " + host + ":" + port);
this.host = host;
this.socket = new Socket(host, port);
this.bis = new BufferedInputStream(this.socket.getInputStream());
this.bos = new BufferedOutputStream(this.socket.getOutputStream());
this.console = new RemoteConsole(this.socket);
initializeCommunication();
System.out.println("Successfully connected!");
new Thread(this, "Client Thread").start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("No server available");
}
}
Thanks
Some routers doesn't allow the internal network to connect to the external IP address of the router.
You can try to use telnet to connect to your server socket. If telnet isn't able to establish a connection, it's likely a networking problem.
Add the java.exe process and the port to your firewall exception list?
edit: Just read you already tried that. All I can suggest is make sure the network is not blocking that port. (routers)
Have You tried running it with JVM option: java.net.preferIPv4Stack=true ?
For what I see in your code, you missed the part where you accept the conection, after instantiating the server socket you need ssocket.accept() to accept conections and then you have to start reading the outputstrem from the socket
I'm building a simple server application, and I can connect to it in the Local Network. But I can't connect over the internet.
This is my Server code:
ServerSocket server;
try {
server = new ServerSocket(4000);
} catch(IOException ex) {
System.out.printf("Could not bind socket 4000\n");
System.exit(1);
}
try {
Socket socket = server.accept();
ClientThread client = new ClientThread(socket);
client.start();
} catch(IOException ex) {
}
And this is the client:
try {
System.out.printf("connecting...\n");
Socket socket = new Socket("mydomain.org", 4000);
System.out.printf("connected!\n");
} catch(UnknownHostException ex) {
ex.printStackTrace();
} catch(IOException ex) {
ex.printStackTrace();
}
I've forwarded port 4000 on my router, which should work. I've forwarded other ports before like 80 and 22.
When I run the client, I get the "connecting..." string, and it hangs there. I don't get "connected!", or a stack trace. But like I said before, it does work on the local network. It works when connecting to 127.0.0.1 and when using 192.168.1.90.
I used CanYouSeeMe.org to check if the port was open. It was successful on port 80, but it times out on 4000.
Check which ip address port 4000 is bound to. It may only be bound to the loopback address (127.0.0.1) instead of any interface.
Not sure which os you're using, but to check:
linux: netstat -ant
windows and mac: netstat -anp tcp
look for the LISTEN line on port 4000 and see whether it's bound to all interfaces (*:4000 or 0.0.0.0:4000), or to a specific interface (127.0.0.1:4000).
If it's not listening on all interfaces, that's your issue - use the constructor that lets you specify the BindAddress.
You've done the experiments to prove that it is not your java and must therefore be a firewall or firewalls issue. Even if you are properly forwarding the ports to your server, the server firewall may not be allowing inbound connections, so check that also.
You have a firewall rule that's throwing away the incoming packets. That's why your client hangs. Check the IP rules on the server computer and on any gateway system to the outside world.