What does socket remote port represent? - javascript

http-client.js:
const http = require('http');
http.get
(
{
port : 9001,
host : 'localhost'
},
(res) =>
{
//...
}
);
tcp-server.js:
const net = require('net');
let server = new net.Server();
server.listen(9001, 'localhost', (err) =>
{
console.log('Started listening', server.address());
});
server.on('connection', (sock) =>
{
console.log(`Connected ${sock.remoteAddress}:${sock.remotePort}`);
});
I run node tc-server.js and then when I run node http-client.js I see output like:
Started listening { address: '127.0.0.1', family: 'IPv4', port: 9001 }
Connected 127.0.0.1:59506
I close http-client.js and run node http-client.js again. I see: Connected 127.0.0.1:59508
I close server and run again, and run the client again, I see Connected 127.0.0.1:59510
So the socket.remotePort is increasing all the time. What I don't understand is why those numbers for ports, I was expecting to see 9001 for port number since that's where the http request was being sent and successfully reached the listening tcp server.

Both sides of a TCP conversation have to have an address and a port. E.g., clients use ports too. What your console.log was telling you was that the client connected to your port 9001 using its port 59506. When your server sends packets to the client, it addresses them with the client's address and that port number, so the TCP layer of the network stack on the client knows what process to send the packet to. (More in the Wikipedia article on TCP.) You see the number increasing just as a byproduct of how your client system assigns available ports to connections.
You don't normally need to care about the client's port.

Related

How to handle partial connection?

I try to create an reverse proxy that work bidirectional. its different from apache that stateless reverse proxy. its means, device can host webserver without public ip. so far i can reverse static content without any problem, css, javascript. but, something like media that return 206 code. it broken in middle. it stop reverse proxy, and try to keep run the server again and again. and i got the video load full. what the problem? i think, it okay already. cause, i jsut forward everything as binary. not specific coding.
reverse proxy port 80 forward to express server in port 8080
import net from 'net';
const server = new net.Server();
server.on('connection', socket => {
socket.on('data', data => {
const client = new net.Socket();
client.connect({
host: '127.0.0.1',
port: 8080
});
client.write(data);
client.on('data', data => {
socket.write(data)
})
})
})
server.listen(80, () => {
console.log('server is running')
});

Cannot connect to MQTT Broker from ReactJS

I'm facing issues while connecting to my local MQTT Broker running in docker.
Here is my connection file:
import mqtt from 'mqtt';
const client = mqtt.connect({
host: 'ws://192.168.31.46',
port: 1883,
});
client.on('connect', () => {
console.log('Connected');
client.subscribe('SEND_MESSAGE', function (topic, message) {
console.log({ topic, message });
});
});
export default client;
The port number is (99.9%) wrong, port 1883 is the native MQTT port not MQTT over WebSockets. What the correct port is will depend on how you have configured the broker (Assuming mosquitto, it does not have a WebSocket listener defined by default)
Also if the mqtt.connect() function is asking for a hostname and port then you shouldn't be give a URL to the post field. Remove the ws:// from the start.

Trouble Catching a UDP packet DGRAM

I have an arduino on LAN emitting UDP packets with some data.
From my laptop using an ssh session with a Pi, both my laptop and Pi are also on the LAN, when I run:
sudo tcpdump -n udp port 8888
Terminal registers the UDP packets
18:14:44.868050 IP 192.168.1.27.8888 > 255.255.255.255.67: BOOTP/DHCP, unknown (0x1a), length 4
I'm a little unsure why it seems that the packet arrives at 255.255.255.255 on port 67 since my arduino is programmed to send to port 8888. The Pi is running the following script:
const dgram = require('dgram');
const catcher = dgram.createSocket('udp4');
catcher.on('listening', () => {
const address = catcher.address();
console.log(`server listening ${address.address}:${address.port}`);
});
catcher.on('message', (msg, rinfo) => {
console.log('Received a Message from: ' + rinfo.address + " Message Code: " + msg.readUInt8(0));
});
catcher.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
});
catcher.bind({
address: "255.255.255.255",
port: 8888,
exclusive: true
});
Which is pretty much identical to the dgram basic documentation but I don't actually see anything show up in the terminal for the packets. I've tried cycling through binding to localhost, define it's local IP manually, when it's just left at catcher.bind(8888) it's bound to 0.0.0.0, and lastly I've tried 255.255.255.255 but no luck. Even tried port 67 just be sure.
Obviously the packets are reaching the Pi as I can see them through tcpdump but I'm unclear as to why they're not getting picked up.
Would any of you know? Cheers!

EPIPE on net.connect to an HTTP server

I am trying to connect to a node http server socket (expressJs) with net.connect in roder to pass that socket to my repl to be able to basically connect to my http server and launch commands.
when trying this I got the error EPIPE the second I started the repl.
here is the code for the repl:
const args = process.argv.slice(2);
if (args.length < 1) {
process.exit(1);
}
const url = args[0];
const [host, port] = url.split(':');
//this will get the url to connect to
const socket = net.connect(parseInt(port), host);
process.stdin.pipe(socket);
socket.pipe(process.stdout);
Console.start({
expose: { container, Metric:metricsObject},
socket:socket
});
The start function :
start(options = {}) {
const { expose, socket } = options;
const repl = REPL.start({
eval: promisableEval,
terminal:true,
input: socket,
output: socket,
});
Object.assign(repl.context, expose);
}
The http server running :
const http = this.express
.listen(this.config.web.port, () => {
const { port } = http.address();
this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
resolve();
});
this.express is just an instance of express : this.express = express();
It looks like you're trying to connect to an http (or https?) server at a URL like http://mine.example.com:3000/path/item by saying
net.connect(parseInt('3000/path/item'), 'http://mine.example.com');
It won't work for a number of reasons.
Unless you're a pretty good programmer expert at the http protocol, you should not use net.connect to talk to http servers. Try using http.clientRequest instead.
hostnames passed to net.connect should be raw machine names like 'mine.example.com' and not preceded by a protocol specifier.
ports, similar.
Sorry, I don't get what you're trying to do with stdin and stdout. But your socket would not be ready for use until its connect operation completes and you get an event announcing that.
You can use the old telnet program to connect to an http server. It lets you type stuff to the server, and then displays what you get back. In your case you'd do
telnet localhost 3000 # from shell your command line
The server then connects and sits there waiting. You type
GET / HTTPS/1.0
and then two <Enter>s. The server then sends back whatever it would send if you put http://localhost:3000 into a browser location line. It then closes the connection.
I'm not sure how that http protocol operation fits into your REPL.
The example you mention at https://medium.com/trabe/mastering-the-node-js-repl-part-3-c0374be0d1bf doesn't connect to an http server, it connects to a tcp server. Http servers (including all node/express servers) are a subspecies of tcp server, but they layer the http protocol on the tcp protocol. The http protocol isn't suitable for the back-and-forth conversational style of REPLs.

Javascript: Can I open websocket server connection at random port

I want to create webserver socket connection at random port. And I want to return server port to calling application or just print it in terminal.
The typical code to create a server connection is as below.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 0 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
So I am trying to create server at port 0. I assume it will create server at random port. How do I get that random port?
I want to know the port number, as soon as server socket is created.
Now I am able to create the websocket server at random port and able to get the port number as well. Not sure if it is the right way, but it works.
const http = require('http');
const WebSocket = require('ws');
const url = require('url');
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection(ws) {
console.log(wss);
});
server.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
});
server.listen(0, '127.0.0.1', function incoming() {console.log (server.address().port);});
Websocket works with http/s on port 80 or 443. The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

Categories

Resources