Open tcp InetSocketAddress to application path (not just host + port) - java

I'm attempting to connect to a TCP socket in Android.
I know the socket service works because I can connect and interact with it in a browser (in JavaScript) as follows:
var ws = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://foo.bar.com:8282/MySocketService', 'my-protocol');
...
So, in my Android app:
This connects successfully, but I never receive messages from it:
SocketAddress sa = new InetSocketAddress("foo.bar.com", 8282);
This fails to connect:
SocketAddress sa = new InetSocketAddress("foo.bar.com/MySocketService", 8282);
and I receive an error like:
java.net.UnknownHostException: Host is unresolved: foo.bar.com/MySocketService:8282
Is there any way to indicate the application path for a TCP service?

TCP end-point is just IP address and a port number. What you are talking about is handled by upper-level protocols on top of TCP, like HTTP, so you need to look at other utilities like java.net.URL.

Related

Reading specific port with PCAP4J

I am currently trying to listen for all UDP Traffic being broadcasted on the network using a specific port. For now lets say the port is 12345. When the data arrives the plan is to redirect the data out port 13579.
Currently I am trying to learn/use the library of PCAP4J. Using the tutorial found on their site (https://www.pcap4j.org/) I have been able to connect and look at data.
Sample Code Thus Far:
InetAddress ip = InetAddress.getByName("127.0.0.1");
PcapNetworkInterface nif = Pcaps.getDevByAddress(ip);
System.out.println("GOT NIF");
PromiscuousMode mode = PromiscuousMode.PROMISCUOUS;
int timeout = 10;
PcapHandle handle = nif.openLive(snapLen, mode, timeout);
System.out.println("GOT HANDEL");
Packet packet = handle.getNextPacketEx();
handle.close();
Questions:
Am I correct in assuming that I am looking at all traffic being sent to 127.0.0.1?
Is there an attribute of the packet that would allow me to say "This packet is on port 12345", or is there a way to configure PCAP4J to only listen to the port of 12345?

TCP socket connection over internet

I am doing a project for which connection between server and client is required.
I did it by adding TCP sockets.
Here is the code fraction :
Server:
ServerSocket welcomeSocket = new ServerSocket(80);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
WorkerThread wt = new WorkerThread(connectionSocket, id);
Thread t = new Thread(wt);
t.start();
workerThreadCount++;
}
Client :
Socket skt = new Socket("192.168.0.108", 80); // The IP address is from cmd->ipconfig/all-> IPv4 Address
outToServer = new PrintWriter(skt.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(skt.getInputStream()));
It all works when both ends are in same device/under same WiFi.But I don't understand what to do for creating connection over internet.
Please help with clear steps.
Here:
Socket skt = new Socket("192.168.0.108", 80);
That is local address. If you want to have a server that is reachable on the internet, then that server needs to have its global public IP address!
In other words: you have to make sure that the server can be reached from the internet somehow. For example by turning to some service provider that hosts servers that you can then equip with your code!
The whole purpose of 192.168 addresses is to be defined only in a local subnet.
Alternatively, you have to check if your ISP has a service where the ISP assigns an IP address to your connection, and that allows calls from the internet to go to your "place".
Meaning: when you want to receive phone calls, you need a phone that is connected to the phone net!
In order to connect to a socket over WAN, you must port forward that port to your local device. This can be done in your routers' settings.
192.168.0.108 --> That's your local IP-address.
This can be used on your local network without any requirements for port forwarding whatsoever. However, to use it over WAN, execute the following steps:
Step 1: Search for your routers' model number and port forwarding on Google on how-to forward port 80 to your local IP-address. Warning: use a static IP-address on your local device to prevent your IP from changing after a reboot.
Step 2: Go to a website like IP Chicken and find your external IP-address.
You can then connect to your socket using:
Socket skt = new Socket("[EXTERNALIP]", 80);
Please be noticed: unless you have a business network, your external IP-address will probably change from time to time.

Java sockets: Client get IP-adress and port to connect to server

I'm stuck at a homework assignment for my university course.
We are supposed to write a game of Rock-Paper-Scissors using Client and Server, choosing TCP or UDP.
The assignment for the client part is:
"Get the IP-address and port of the server at the beginning and than use this information to connect to the server."
And server:
"The port needs to be set to a number between 10000 and 20000 at the start using command line input."
Now this got me wondering. How is the Client supposed to get the Ip-Adress and port of the server if it is not connected to the server yet?
And normally the client and the server creates a socket and the server listens if a client wants to connect and then accepts the request, making a connection, not the client, like it is requested in the assignment. Isn't it impossible to know the server, if not connected yet?
I got a version working, if the server goes:
// Setting the port via console, making an output: "please enter valid port" and returns the entered port number
ServerTest.port = ServerTest.getPort();
...
ServerSocket testSocket = new ServerSocket(ServerTest.port);
and the client:
private static String host = "localhost";
private static Integer port = 1337;
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
if I set the port to 1337 when starting the server.
Then I tried something like
//Client
port = ServerTest.getServerPort();
...
Socket clientSocket = new Socket(ClientTest.host, ClientTest.port);
and in the server-class:
public static Integer getServerPort(){
return port;
}
But that throws an "Connection refused"-exception, even if I first the server at first, set the port and than start the client.
Does anyone have an idea how to solve this?

Java.net.SocketException: Permission denied: connect

I have two PCs in one network that I want to connect. One of them should send a notification to the other via TCP. One the one PC I have a "server" (Python script) socket which waits for the "client"(Jar file) to send a specific String and then it gives me a notification. This works perfectly fine when I'm trying it out one one PC. But when I want to do the intended action the "client" PC's .jar gives me an error that the connection is refused. Do I have to open a specific port on the other PC or what else could cause trouble? One PC runs Fedora the other Windows 8
"Server Code"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 5005))
s.listen(1)
try:
while True:
komm, addr = s.accept()
while True:
data = komm.recv(1024)
if data == "$":
noty()
if not data:
komm.close()
break
finally:
s.close()
"Client" Code
public static void main(String[] args) throws Exception {
Socket socket = new Socket("192.168.178.25", 5005);
OutputStream out = socket.getOutputStream();
String dat = "$";
out.write(dat.getBytes());
socket.close();
}
Your server is probably binding to the wrong interface,
calling
s.bind(("", 5005))
Without setting an interface will allow the program to pick what ip address / interface it will connect to.
Since your client is trying to connect to ("192.168.178.25", 5005); you may want to put an IP address into the bind call to prevent the server picking the wrong ip interface.
Example:
s.bind(("192.168.178.25", 5005))
if its permission denied then something is blocking your connection with the computer. i would try to open a port and see if that works. if you want an example of java sockets you can take a look at my SUPER Tic-Tac-Toe Multiplayer it uses java sockets to send strings to the clients as a way to represent what actions the clients should take.

Netty is giving me a wrong port using TCP

I'm using Netty with Java trying to configure a TCP client. Everything is working so far, except that I'm connecting on port 1050 but when I call messageEvent.getRemoteAddress() on messageReceived() method of the handler, I'm getting the port 1500. I changed the port to 1049 but I'm still receiving 1500. This is Netty's problem or can it be the server's problem?
My hardware setup here is: this netty client running on a Java server, and several access control equipments spread through the area here. The equipments act as tcp servers and the netty as the client, that process everything the server sends and just reply to them.
The tcp server initialization is this:
private ChannelFactory fabrica;
private ServerBootstrap bootstrap;
public void iniciarServidorTCP() {
fabrica = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
bootstrap = new ServerBootstrap(fabrica);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoderDeMensagem", new MensagemDecoderTCP());
pipeline.addLast("handlerGerente", new GerenteTCP());
pipeline.addLast("encoder de mensagem", new MensagemEncoderTCP());
return pipeline;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.bind(new InetSocketAddress(1050));
}
Any idea why I'm getting 1500 instead of 1050? Could it be a problem with the equipment?
Every TCP connection has a source port and a destination port. When you connect to a server, the server sees the destination port as its well-known address. The client picks the source port. On either end, getting the "remote address" gets the other side's address. So when you call get remote address on the server, you get the client's address, not the server's.
Imagine you have a server with one IP address and one well-known port. Now, say you have a client machine with one IP address. If it make's four connections to the server, how can either end tell those connections apart? The answer is that the client port is different.

Categories

Resources