I am getting a different port number than I use - java

I have 2 java programs, Server and Client.
I am trying to connect the client program to the server program using java socket programming.
Here is the Server program :
public class ServerX {
public static void main(String[] args) {
ServerSocket ss = new ServerSocket(987);
Socket s = ss.accept();
InetSocketAddress isa1 = (InetSocketAddress) s.getRemoteSocketAddress();
System.out.println(isa1.getPort());
ss.close();
}
}
And here is the Client program :
public class ClientX {
public static void main(String[] args) {
Socket s = new Socket("ip of the server", 987);
s.close();
}
}
I expected that isa1.getPort() in the Server program gives 987, but it actually gives 52532 instead.
So what is the problem, and what 53532 means?

TCP is a full duplex communication protocol it means both side of an established connection allowed to send and received data.
so server is listening on port 987 but client side also need a port on it's own side to receive data that is being sent from server side and about the connection in case of ClientX, server will listen to incoming requests on port number 987 but if want sent something as reply to ClientX will write on port 53532 of the connection

Not sure on requirement over here. But if you wish to perform a sanity check on Static port and usage of Java is not a pre-cursor, then I feel below script must help you. I had referred to Python Docs (https://docs.python.org/2.6/library/socket.html) for getting help in past for one of my project requirement.
''' Simple socket server using threads
'''
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 61901 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
Herein PORT = 61901 can be replaced with required port.

Related

ServerSocket.getLocalSocketAddress() returning empty

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?

Client socket not connecting to server socket

I'm trying to transfer a message between two android phones over the local network. I read sockets where a good way to do this.
(I cant use bluetooth)
(I cant use NFC either)
I have built a server and client application.
One app has a server that listens for a connection.
The other app has a client that tries to connect when a button is pressed.
Both the manifest files contain the correct permissions. (with the html tags)
uses-permission android:name="android.permission.INTERNET" /
uses-permission >android:name="android.permission.ACCESS_NETWORK_STATE"/
I put the server online first:
ServerSocket myServerSocket = new ServerSocket(27024);
System.out.println("Server is waiting for incoming connection on host=" + InetAddress.getLocalHost().getCanonicalHostName() + ", port=" + myServerSocket.getLocalPort());
Socket socket = myServerSocket.accept();
Then try and connect with the client.
String host = "localhost";
int port = 27024;
try{
System.out.println("Client attempting to connect to server at host: " + host + ", port: " + port);
Socket socket = new Socket(host, port);
//This below line never gets called :(
System.out.println("Client socked created! Now trying to send data to server");
}
In my console:
Client attempting to connect to server at host: localhost, port: 27024
The "Client socked created!" line never gets output.
Both hosts are set to "localhost" and the port number is the same.
I've tried various ports, but nothing happens.
String host = "localhost";
int port = 27024;
You realize that your client needs to be given the IP address of the server, right?
Note you will most likely not be able to, or ever should, bind an app on a non WiFi interface.

How to run a simple socket server that allows incoming connections?

I am trying to build a very simple socket server in JAVA that my Flash application can listen to. I am using this tutorial. Everything seems to be working - the JAVA code is compiled and the server is running.
My question is: how can external applications send messages to this server using just an IP address and a port number? My goal is that flash can listen to socket messages sent by an external application.
The Java code:
import java.io.*;
import java.net.*;
class SimpleServer {
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args) {
int port = 8080;
try {
port = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port) {
System.out.println(">> Starting SimpleServer");
try {
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(
new InputStreamReader(
incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done) {
String str = readerIn.readLine();
if (str == null) {
done = true;
} else {
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
done = true;
}
incoming.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
private void out(String str) {
printOut.println(str);
System.out.println(str);
}
}
Maybe I don't understand correctly your problem description, but if you create the server in Java, it listens to its port and not your Flash application. If you want your Flash application to wait for messages from other applications, it must have a server role and listen to a TCP port the same way as this Java server does.
You can connect to and test the given Java server easily by telnet program (available in all operating systems) by providing a host name or an IP address and a port as parameters:
telnet 127.0.0.1 8080
Any other application can connect in a similar way, using just a hostname/IP address and a port. For example in Java, you can create a client socket:
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
By not specifying an IP address for your socket, it will listen on 0.0.0.0 (all interfaces).
In fact, that will usually be your computer's IP / the server's IP.
Assuming that your application runs on your computer at home, there are three cases that cover most of the connection situations:
Connecting from the same machine:
Use 127.0.0.1:8080
Connecting from the same LAN (e.g. your brother's PC):
Use your LAN IP (e.g. 192.168.1.4:8080)
Connecting from WAN (outside your routers LAN) (internet e.g.):
Use your WAN IP.(e.g. 84.156.74.194). There are plenty websites, that tell you your WAN IP like this
You may have to setup your router, to forward the port 8080 to your PC
For simple connection tests, one could use a telnet client.
I think you are missing the point of client/server socket applications.
If you are building the socket server (with whatever programming language you chose), you will then need to connect with (a) socket client(s) to this server. After a connection is successfully established (persistent) between the client and the server, you can start what ever kind of communication you have implemented between them.
The server always acts as the passive, the client as active part in a socket server/client constellation.
I was checking the link that you are referring to. In that, the procedure to create a stand-alone server is mentioned which is the code that you have pasted as well.
According to the link, the application acts as the client and uses the XMLSocket methods to connect to this server. This application is the flash application that you are talking about. As mentioned in the link, by using the following code any flash application can connect and talk to the server:
var xmlsock:XMLSocket = new XMLSocket();
xmlsock.connect("127.0.0.1", 8080);
xmlsock.send(xmlFormattedData);
When you mention
My goal is that flash can listen to socket messages sent by an external application.
its actually the flash application that is the client and it cannot listen unless programmed to act as a server. I hope this provides some clarity!

Socket: could not connect to server or specific port

I am trying to connect server by port and Host Name.
I find one program but when i am trying to run it will show following Exception
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sample.Echoclient2.main(Echoclient2.java:31)
Couldn't get I/O for the connection to: 127.0.0.1
Java Result: 1
Here is my code which i use.
public class Echoclient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10008);
System.out.println("server name"+Inet4Address.getByName(serverHostname));
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
System.out.println("Connection accepted " +
echoSocket.getInetAddress() + ":" +
echoSocket.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
What i need:
1. I need to send some message to server and want response from server. Suppose i send "I am user of stackoverflow" then server should give any response like return same String or convert in uppercase or something else.
Some Questions:
1. I write client Java File but whether i need to write server java file.
2. Can we send request by using ip and port.
3. Can we use host name.
4. Any echo server name? i need to send message to this server want to know response.
5. I try both server,java and client.java then i got result? is this solution for me.
1. I write client Java File but whether i need to write server java file.
Yes, you either need to write your own server (if the server should fulfill some unique requirements) or connect to an existing one. The message "connection refused" indicates that no server is running at the port you are trying to connect to.
2. Can we send request by using ip and port.
Yes.
3. Can we use host name.
Yes. You need either IP or hostname, and the port.
4. Any echo server name? i need to send message to this server want to know response.
You can setup an echo server on your machine so that you can first focus on coding your client. There is a Standard Echo server defined at port 7. Setup depends on your operating system environment - On Ubuntu Linux, I had to install the xinetd package and enable the echo server in /etc/xinetd.d/echo. Then, you can verify if the server is running by using the telnet program:
andreas#ubuntu:~$ telnet localhost 7
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
Hello
Using telnet to connect to any port is also a common technique to verify if a server is running and reachable. With the example from your question, you could check with telnet 127.0.0.1 10008 whether a server is running on the port you specified - you will get the same connetion refused as from your Java program if no server is available.
5. I try both server,java and client.java then i got result? is this solution for me.
Not sure which server and client you are referring to.
Some additional references:
All about sockets (also includes "Writing a Client/Server pair")
Enabling desired xinetd protocols
Java Tutorial: Echo client in Java
You have to run your server program also in local host. You are getting this exception because of 10008 port not ruining on your machine.
Some Question:
I write client Java File but whether i need to write server java file.
either you can write a server program or you can connect to a remote server. In that
case you should have both ip and running port in remote server.
Can we send request by using ip and port.
Yes You required both to send a message.
Can we use host name.
If you machine can resolve your host name you can do it. Otherwice you can use ip address
Any echo server name? i need to send message to this server want to know response.
I have no idea about this , need to search on web.
I try both server,java and client.java then i got result? is this solution for me.
Yes.

In TCP MultiThreaded Server, if a client gets service ,how to find the port number of servicing socket?

In TCP Multi Threaded Server, if a client gets service ,how to find the port number of servicing socket?
From Sun Java tutorials
When a connection is requested and successfully established, the accept() method returns a new "Socket object" which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket.
How can I find the port number of the "Socket object"?
Does Socket.getPort() not do what you want? Or do you mean you want the local port (again, there's Socket.getLocalPort()? If you could give a worked example of what you're after, it would be easier to understand.
Here's a short example:
import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(50000);
while (true) {
Socket s = ss.accept();
System.out.println("Local: " + s.getLocalPort() +
"; Remote: " + s.getPort());
}
}
}
If you run that code and connect to it multiple times, you'll get output something like this:
Local: 50000; Remote: 17859
Local: 50000; Remote: 17866
Local: 50000; Remote: 17872
So getLocalPort() returns the port that was specified in the ServerSocket constructor, but getPort() returns a different port each time.

Categories