This question already has an answer here:
java.net.ConnectException: Connection refused TCP
(1 answer)
Closed 6 years ago.
I have to establish a TCP connection to a server, which requires that I send the credential to logon in the format:
<STX>username=fred&password=123456<ETX>
Let's say host: qstage.thetcphost.com and port:8999
I am new to socket programming and using the same to implement this. I have used java.net.Socket at the client side but I dont know how do I send the above string for authentication to the TCP Server in Java.
I am able to telnet the server now.
But how do I pass the credential string in the < STX >...< ETX > format after (or during):
Socket socket = new Socket("mshxml.morningstar.com", 8999);
I mean what is the piece of code that I have to write to authenticate myself to the TCP server?
I have searched this site for this info but could not find any.
Help would be greatly appreciated.
Establish the socket connection is the first step before you can send any creds information.
If this step is failing, consider the specs from your target server. Is the correct port provided? Any consideration on protocol?
Usually, the authentication will be happen after you have already established successfully the connection.
Editted: Add source code for writing to socket from a socket client.
Now, in this context, you're a socket client, try to send creds to server.
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Sample found here: http://www.tutorialspoint.com/java/java_networking.htm
Related
I have started a client in my system. It is running on port no 7913. I am sending a request data via TCP/IP from Java to server socket running on 7913.
log is Message sent to Socket [addr=/190.161.153.109,port=7913,localport=54717]
I have also received the response from server for that particular data. Now the server is also trying to send a request to my localport 54717, not to port where my application is listening [ie 7913].
How to handle the request? When I try to connect with telnet to my localport, connection is refused.
The code:
public static String ickTransport(String ickHeader,String ickdata, Socket connection) throws UnknownHostException, IOException
try
{
connection.setSoTimeout(Integer.parseInt(ickTimeOut));
log.debug("ick Message for "+connection.toString()+" is " + ickMessage);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
DataOutputStream osw = new DataOutputStream(bos);
osw.writeShort(Integer.parseInt(ickHeader));
osw.writeBytes(ickMessage);
osw.flush();
DataInputStream stream = new DataInputStream(connection.getInputStream());
int numberRecords = stream.readShort();
if (numberRecords > 0) {
int nSizeRead = 0;
byte[] bRequest = new byte[numberRecords];
int nSizeBuffer;
for (; numberRecords > 0; numberRecords -= nSizeBuffer) {
byte[] bBuffer = new byte[numberRecords];
nSizeBuffer = stream.read(bBuffer);
System.arraycopy(bBuffer, 0, bRequest, nSizeRead, nSizeBuffer);
nSizeRead += nSizeBuffer;
}
ickResponse = new String(bRequest);
log.debug("Response from ick is " + ickResponse);
}
}
catch (SocketTimeoutException e)
{
log.error(e.getMessage());
}
return ickResponse;
To understand what is going on you should understand what is listen socket and how it differs from connection socket.
When your application listens it (this ServerSocket does):
Attaches to the port that you specify in bind request or in constructor
Ask JVM to receive new connection on that port
When connection is received listen socket changes it state and provide you new socket for new connection with accept method.
When your application establishes NEW connection it use connect method. Unless you use bind request on socket it:
Allocates new dynamic port (54717 in your example)
Sends connect request to the server
After connection established you can use it for sending/receiving requests to/from server
Because nobody listens this dynamic port telnet requests are refused on it.
I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
Console.WriteLine("The server is running at port 13...");
Console.WriteLine("The local End point is -" +
tcpListener.LocalEndpoint);
output = "Waiting for a connection...";
Console.WriteLine(output);
Socket s = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
catch (Exception e)
{
output = "Error: " + e.ToString();
Console.WriteLine(output);
}
}
On the Java side, I have created a socket which listens to the same host and port -
Socket socket;
try {
socket = new Socket( "localhost", 13);
System.out.println("Connection established");
BufferedReader input =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?
I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.
I've wrote simple client (using SocketChannel):
User friend = database.getUserByName("jonh");
SocketChannel friendSkt = SocketChannel.open(new InetSocketAddress(InetAddress.getByName(friend.getHost()), friend.getPort()));
System.out.println("Local: " + friendSkt.socket().getLocalSocketAddress()
+ " |Remote: "+ friendSkt.socket().getRemoteSocketAddress());
and server (using simple Socket):
ServerSocket skt = new ServerSocket(0);
Socket server = skt.accept();
InputStream x = server.getInputStream();
System.out.println("Local: " + server.getLocalSocketAddress() + " |Remote: "+ server.getRemoteSocketAddress());
Even if connect returns no exception and client write on socket (simple getOutputStream.write(...)), server not read and returns -1. So I've printed the address of each socket and found this:
CLIENT: Local: /192.168.0.2:58981 |Remote: /192.168.0.2:58968
SERVER: Local: /192.168.0.2:58968 |Remote: /192.168.0.2:58980
It is normal that client local port is server remote port+1 instead to being the same value?
I want to do UDP Hole Punching with two clients with the help of a server with a static IP. The server waits for the two clients on port 7070 and 7071. After that it sends the IP address and port to each other. This part is working fine. But I'm not able to establish a communication between the two clients. I tried the code in different Wifi networks and in 3G mobile network. The client program throws the IO-Exception "No route to host".
The client code is used for both clients. Once executed with port 7070 and once with 7071.
Do you think I've implemented the UDP hole punching concept correctly? Any ideas to make it work?
Here's the server code first, followed by the client code.
Thank you for help.
Code of server:
public class UDPHolePunchingServer {
public static void main(String args[]) throws Exception {
// Waiting for Connection of Client1 on Port 7070
// ////////////////////////////////////////////////
// open serverSocket on Port 7070
DatagramSocket serverSocket1 = new DatagramSocket(7070);
System.out.println("Waiting for Client 1 on Port "
+ serverSocket1.getLocalPort());
// receive Data
DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
serverSocket1.receive(receivePacket);
// Get IP-Address and Port of Client1
InetAddress IPAddress1 = receivePacket.getAddress();
int port1 = receivePacket.getPort();
String msgInfoOfClient1 = IPAddress1 + "-" + port1 + "-";
System.out.println("Client1: " + msgInfoOfClient1);
// Waiting for Connection of Client2 on Port 7071
// ////////////////////////////////////////////////
// open serverSocket on Port 7071
DatagramSocket serverSocket2 = new DatagramSocket(7071);
System.out.println("Waiting for Client 2 on Port "
+ serverSocket2.getLocalPort());
// receive Data
receivePacket = new DatagramPacket(new byte[1024], 1024);
serverSocket2.receive(receivePacket);
// GetIP-Address and Port of Client1
InetAddress IPAddress2 = receivePacket.getAddress();
int port2 = receivePacket.getPort();
String msgInfoOfClient2 = IPAddress2 + "-" + port2 + "-";
System.out.println("Client2:" + msgInfoOfClient2);
// Send the Information to the other Client
// /////////////////////////////////////////////////
// Send Information of Client2 to Client1
serverSocket1.send(new DatagramPacket(msgInfoOfClient2.getBytes(),
msgInfoOfClient2.getBytes().length, IPAddress1, port1));
// Send Infos of Client1 to Client2
serverSocket2.send(new DatagramPacket(msgInfoOfClient1.getBytes(),
msgInfoOfClient1.getBytes().length, IPAddress2, port2));
//close Sockets
serverSocket1.close();
serverSocket2.close();
}
Code of client
public class UDPHolePunchingClient {
public static void main(String[] args) throws Exception {
// prepare Socket
DatagramSocket clientSocket = new DatagramSocket();
// prepare Data
byte[] sendData = "Hello".getBytes();
// send Data to Server with fix IP (X.X.X.X)
// Client1 uses port 7070, Client2 uses port 7071
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName("X.X.X.X"), 7070);
clientSocket.send(sendPacket);
// receive Data ==> Format:"<IP of other Client>-<Port of other Client>"
DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
clientSocket.receive(receivePacket);
// Convert Response to IP and Port
String response = new String(receivePacket.getData());
String[] splitResponse = response.split("-");
InetAddress ip = InetAddress.getByName(splitResponse[0].substring(1));
int port = Integer.parseInt(splitResponse[1]);
// output converted Data for check
System.out.println("IP: " + ip + " PORT: " + port);
// close socket and open new socket with SAME localport
int localPort = clientSocket.getLocalPort();
clientSocket.close();
clientSocket = new DatagramSocket(localPort);
// set Timeout for receiving Data
clientSocket.setSoTimeout(1000);
// send 5000 Messages for testing
for (int i = 0; i < 5000; i++) {
// send Message to other client
sendData = ("Datapacket(" + i + ")").getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
clientSocket.send(sendPacket);
// receive Message from other client
try {
receivePacket.setData(new byte[1024]);
clientSocket.receive(receivePacket);
System.out.println("REC: "
+ new String(receivePacket.getData()));
} catch (Exception e) {
System.out.println("SERVER TIMED OUT");
}
}
// close connection
clientSocket.close();
}
UPDATE
The code is generally working. I've tried it in two different home networks now and it's working. But it isn't working in my 3G or university network. In 3G, I verified that the NAT is mapping the two ports (the client port and by the router assigned port) together again, even after closing and opening the clientSocket. Has anyone an idea why it isn't working then?
UDP hole punching can't be achieved with all types of NAT. There is no universal or reliable way defined for all types of NAT. It is even very difficult for symmetric NAT.
Depending on the NAT behaviour, the port mapping could be different for different devices sending the UDP packets.
Like, If A sends a UDP packet to B, it may get some port like 50000. But if A sends a UDP packet to C, then it may get a different mapping like 50002. So, in your case sending a packet to server may give a client some port but sending a packet to other client may give some other port.
You shall read more about NAT behaviour here:
https://www.rfc-editor.org/rfc/rfc4787
https://www.rfc-editor.org/rfc/rfc5128
UDP hole punching not going through on 3G
For symmetric NAT (3G network connecting to a different mobile network), you need to do Multi-UDP hole punching.
See:
https://drive.google.com/file/d/0B1IimJ20gG0SY2NvaE4wRVVMbG8/view?usp=sharing
http://tools.ietf.org/id/draft-takeda-symmetric-nat-traversal-00.txt
https://www.goto.info.waseda.ac.jp/~wei/file/wei-apan-v10.pdf
http://journals.sfu.ca/apan/index.php/apan/article/view/75/pdf_31
Either that or relay all the data through a TURN server.
You rightly use a rendezvous server to inform each node of the others IP / port based on the UDP connection. However using the public IP and port which is the combination which will is obtained by the connection as you have, means that in scenarios where both hosts exist on the same private network hairpin translation is required by the NAT which is sometimes not supported.
To remedy this you can send the IP and port your node believes itself to have in the message to the server (private ip / port) and include this in the information each node receives on the other. Then attempt a connection on both the public combination (the one you are using) and the one I just mentioned and just use the first one which is successfully established.
trying to connect via TCP to a server using java sockets, the connection gets refused. I'm supposed to send a key to authenticate. code:
Socket clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("server.address.whatever", 123456));
System.out.println("Connected");
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String key = "key";
outToServer.writeBytes(key + "\r\n");
String response = inFromServer.readLine();
System.out.println("FROM SERVER: " + response);
clientSocket.close();
It never makes it to the point where it tries to print out "Connected", it throws
java.net.ConnectException: Connection refused
So i never send the key. What am i missing here? How can i send an initial message during connecting? Am i even supposed to do that?
It sounds like there is no server process listening on that socket. Check whether you can make a connection with a tool like nmap (or just telnet).