Simple-peer WebRTC Error: Ice connection failed - node.js

I can not make the Simple-Peer NPM library to connect between two computers in two different networks in Browser. If the computers are in the same local network, the browsers connect each other, but otherwise, I can not make them connect.
Both browsers return this error:
"Error: Ice connection failed.
at Peer._onIceStateChange"
at RTCPeerConnection.Peer.self._pc.oniceconnectionstatechange
The signalling looks right for me:
{ type: 'offer',
sdp: 'v=0\r\no=- 2275520429720515716 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE data\r\na=msid-semantic: WMS\r\nm=application 49523 DTLS/SCTP 5000\r\nc=IN IP4 5.12.206.160\r\na=candidate:2020300070 1 udp 2113937151 192.168.2.8 49523 typ host generation 0 network-cost 50\r\na=candidate:842163049 1 udp 1677729535 5.12.206.160 49523 typ srflx raddr 192.168.2.8 rport 49523 generation 0 network-cost 50\r\na=ice-ufrag:Ph/x\r\na=ice-pwd:csnTbzHs+dxzakEKPY8LfvBg\r\na=fingerprint:sha-256 B9:C0:9D:91:46:1B:E8:5C:83:B1:11:A7:C5:D7:64:97:A6:63:D9:12:11:0F:9A:05:8F:46:83:BC:90:38:86:9E\r\na=setup:actpass\r\na=mid:data\r\na=sctpmap:5000 webrtc-datachannel 1024\r\n' } }
{ type: 'answer',
sdp: 'v=0\r\no=- 1356997482353729498 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE data\r\na=msid-semantic: WMS\r\nm=application 56005 DTLS/SCTP 5000\r\nc=IN IP4 86.126.104.54\r\nb=AS:30\r\na=candidate:2702239670 1 udp 2113937151 192.168.1.103 56003 typ host generation 0 network-cost 50\r\na=candidate:842163049 1 udp 1677729535 86.126.104.54 56005 typ srflx raddr 192.168.1.103 rport 56003 generation 0 network-cost 50\r\na=ice-ufrag:W6zA\r\na=ice-pwd:1NhU5D47rSz83ANxlY+Tz/XI\r\na=ice-options:trickle\r\na=fingerprint:sha-256 2C:0B:78:49:F5:F0:44:6C:86:DD:27:BC:B6:7D:77:B9:B1:07:F4:2F:37:F5:24:D9:A3:54:7D:B3:A0:3C:57:C0\r\na=setup:active\r\na=mid:data\r\na=sctpmap:5000 webrtc-datachannel 1024\r\n' } }
but when the library wants to establish the connection, both browsers return the above-mentioned error.
This my code
//TUTORIAL BASED ON
// https://github.com/feross/simple-peer
var initiator = (location.hash||'') === '#1';
console.log("inititator",location.hash , initiator);
var Peer = require('simple-peer');
params = {
initiator: initiator,
trickle: false,
reconnectTimer: 100,
iceTransportPolicy: 'relay',
config: {
iceServers: [
{
urls: "stun:numb.viagenie.ca",
username: "pasaseh#ether123.net",
credential: "12345678"
},
{
urls: "turn:numb.viagenie.ca",
username: "pasaseh#ether123.net",
credential: "12345678"
}
]
}
};
if (typeof window === "undefined"){
var wrtc = require('wrtc');
params.wrtc= wrtc;
}
var p = new Peer(params);
p.on('error', function (err) { console.log('error', err) })
p.on('signal', function (data) {
console.log('SIGNAL', JSON.stringify(data));
document.querySelector('#outgoing').textContent = JSON.stringify(data)
});
document.querySelector('form').addEventListener('submit', function (ev) {
ev.preventDefault();
console.log("am apasat pe button");
p.signal(JSON.parse(document.querySelector('#incoming').value))
});
let index = Math.floor(Math.random()*100);
p.on('connect', function (data) {
console.log('CONNECT', data, p);
setInterval(function() {
if ((typeof p !== 'undefined')&& ( p !== null)) {
console.log(p);
p.send('whatever' + index + " ___ " + Math.random())
}
}, 500);
p.on("hello", function(data){
alert(data);
});
p.emit("hello",55);
})
p.on('data', function (data) {
console.log('data: ' + data)
});
module.exports = function(){
console.log("Hello World Server");
};
webrtc-internals
Any solution to this problem? Thanks

The screenshot from chrome://webrtc-internals shows that despite the TURN server credentials you use, no icecandidate with type relay is gathered. See this blog post for details.
You can check the credentials using this page

i suggest using still working ice servers when listing your ice server as below
new SimplePeer({
initiator: false,
tricle: false,
config: {
iceServers: [
{
urls: "turn:numb.viagenie.ca",
credential: "muazkh",
username: "webrtc#live.com",
},
],
},
})

Related

Check several different TCP/IP services for availability?

Let's say I have a list of hostnames and ports, not all of which are HTTP related.
var config = {
"checks": [
{
"name": "NPM",
"hostname": "npmjs.com",
"port": 80
},
{
"name": "AWS",
"hostname": "aws.amazon.com",
"port": 443
},
{
"name": "RabbitMQ",
"hostname": "merry-butterfly.rmq.cloudamqp.com",
"port": 5671
}
]
}
What is an effective way to test that each of these services can be reached? My first thoughts were to use a typical telnet-like approach, I did this:
var telnet = require('telnet-client')
config.checks.forEach(function(check) {
var connection = new telnet()
var params = {
host: check.hostname,
port: check.port,
negotiationMandatory: false
}
connection.on('connect', function() {
connection.send('GET /', {
ors: '\r\n',
waitfor: '\n'
}, function(err, data) {
console.log(err, data);
connection.end()
})
})
connection.connect(params)
results.push(result);
});
The above seems to work, but I'm actually not sure what data to send to each individual services to get back a response that suggests the service is "reachable", I don't need to auth or do any operations with the service, just check that it can be reached. Additionally it raises an exception if the DNS is unreachable:
Error: getaddrinfo ENOTFOUND merry-butterfly.rmq.cloudamqp.com/api merry-butterfly.rmq.cloudamqp.com/api:443
What would be the appropriate way to handle the errors, and async test each of the entries in the list of "checks"?
Ping the host.
https://www.npmjs.com/package/ping
For example:
var ping = require('ping');
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
hosts.forEach(function(host){
ping.sys.probe(host, function(isAlive){
var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
console.log(msg);
});
});

OpenShift : Error implementing DNS Client using nodejs [SOLVED]

I am implementing a DNS Lookup client on OpenShift using Nodejs and "native-dns" is the npm module. However I am getting the below mentioned error whenever I try to lookup for the DNS records of the domain using 8.8.8.8 as the DNS server IP.
events.js:72
throw er; // Unhandled 'error' event
^ Error: bind EACCES
at errnoException (dgram.js:458:11)
at dgram.js:211:28
at dns.js:72:18
at process._tickCallback (node.js:442:13)
the code for the function is as follows
function DNS_Domain_Lookup_function(dns,domain_name,rbl, ns_ip, record_type ,DNS_cb) {
var dns_response = '';
var question = dns.Question({
name: domain_name + rbl,
type: record_type,
});
var req = dns.Request({
question: question,
server: { address: ns_ip, port: 53, type: 'udp' },
timeout: 4000,
});
req.on('timeout', function () {
if (rbl === '') {
rbl='query'
}
dns_response = { question: [ { name: domain_name + ',' + rbl} ], answer: [ { name: rbl, address: 'timeout' } ]};//Clean(2)
DNS_cb(dns_response); //work on this to get the exact output
});
req.on('message', function (err, answer) {
rbl !== '' ? (answer.question[0].name = domain_name + ',' + rbl) : (answer.question[0].name = domain_name);
DNS_cb(answer);
});
req.on('end', function () {
});
req.send();
}
Update : Cannot Implement DNS Server on OpenShift.

Socket.get callback not triggered in socket.on function

I've been stuck on this issue for a while the answer might be really basic but I fail to understand what the problem is. AFAIU It execute the function but doesnt trigger the callback and I dont know why.
My script aim to have both a tcp server to have a device (raspberry pi) that connect a tcp socket and a client to connect to a websocket on a sailsjs app.
I manage to have both this thing running on the following code, the problem is they only work separatly, simultanuously but separatly, when I try a get outside the socket everything works fine but when I do inside, the io.socket object is just piling up the get request in a requestQueue.
{ useCORSRouteToGetCookie: true,
url: 'http://localhost:1337',
multiplex: undefined,
transports: [ 'polling', 'websocket' ],
eventQueue: { 'sails:parseError': [ [Function] ] },
query:'__sails_io_sdk_version=0.11.0&__sails_io_sdk_platform=node&__sails_io_sdk_language=javascript',
_raw:
{ socket:
{ options: [Object],
connected: true,
open: true,
connecting: false,
reconnecting: false,
namespaces: [Object],
buffer: [],
doBuffer: false,
sessionid: '0xAlU_CarIOPQAGUGKQW',
closeTimeout: 60000,
heartbeatTimeout: 60000,
origTransports: [Object],
transports: [Object],
heartbeatTimeoutTimer: [Object],
transport: [Object],
connectTimeoutTimer: [Object],
'$events': {} },
name: '',
flags: {},
json: { namespace: [Circular], name: 'json' },
ackPackets: 0,
acks: {},
'$events':
{ 'sails:parseError': [Function],
connect: [Object],
disconnect: [Function],
reconnecting: [Function],
reconnect: [Function],
error: [Function: failedToConnect],
undefined: undefined } },
requestQueue:
[ { method: 'get', headers: {}, data: {}, url: '/', cb: [Function] },
{ method: 'get', headers: {}, data: {}, url: '/', cb: [Function] } ] }
The code is the following :
//library to connect to sailsjs websockets
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');
//library to do the tcp server
var net = require('net');
// Instantiate the socket client (`io`)
// (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
var io = sailsIOClient(socketIOClient);
// Set some options:
// (you have to specify the host and port of the Sails backend when using this library from Node.js)
io.sails.url = 'http://localhost:1337';
var server = net.createServer(function(tcpSocket) { //'connection' listener
//socket was sucessfully connected
console.log('client connected');
//notify on deconnection
tcpSocket.on('end', function() {
console.log('client disconnected');
});
// Handle incoming messages from clients.
tcpSocket.on('data', function (data) {
console.log(data.toString('utf8', 0, data.length));
//if data is PING respond PONG
if(data.toString('utf8', 0, 4)=='PING'){
console.log('I was pinged');
tcpSocket.write('PONG\r\n');
}
console.log(io.socket);//debugging purpose
//trigger a socket call on the sails app
io.socket.get('/', function (body, JWR) {
//display the result
console.log('Sails responded with: ', body);
console.log('with headers: ', JWR.headers);
console.log('and with status code: ', JWR.statusCode);
});
});
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
It looks like your socket isn't autoconnecting. Try connecting manually:
// Instantiate the socket client (`io`)
// (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
var io = sailsIOClient(socketIOClient);
// Set some options:
// (you have to specify the host and port of the Sails backend when using this library from Node.js)
io.sails.url = 'http://localhost:1337';
var socket = io.sails.connect();
socket.on('connect', function() {
... connect TCP server and continue ...
});
I found a solution, I just got rid of sails.io.js and used plain socket.io it now works as intended feel free to explain though why it didnt in sails.io.js
//library to connect to sailsjs websockets
var socketIOClient = require('socket.io-client');
//var sailsIOClient = require('sails.io.js');
//library to do the tcp server
var net = require('net');
var socket=socketIOClient.connect('http://localhost:1337', {
'force new connection': true
});
var server = net.createServer(function(tcpSocket) { //'connection' listener
//socket was sucessfully connected
console.log('client connected');
//notify on deconnection
tcpSocket.on('end', function() {
console.log('client disconnected');
});
// Handle incoming messages from clients.
tcpSocket.on('data', function (data) {
console.log(data.toString('utf8', 0, data.length));
console.log(data.toString('utf8', 0, data.length));
//if data is PING respond PONG
if(data.toString('utf8', 0, 4)=='PING'){
console.log('I was pinged');
tcpSocket.write('PONG\r\n');
}
if(data.toString('utf8', 0, 4)=='test'){
socket.emit('test',{message : 'test'});
//io.socket.disconnect();
}
});
});

peerjs connection opens, but no data is received

Here's my setup
Server
var webrtcServer = new PeerServer({
port: 9000,
path: "/wrtc"
});
Peer 1 (running inside a node-webkit application)
var peer = new Peer( 'masterName', {
host: 'localhost',
port: 9000,
path: '/wrtc'
});
peer.on( 'connection', function(conn) {
conn.on( 'open', function() {
console.log( "peer connected" ); // This fires as expected
conn.send( "helo" );
});
});
Peer 2 (running inside a browser)
conn = peer.connect('masterName');
conn.on('open', function(){
console.log( "WebRTC connection open" ); // This fires as expected
});
conn.on('data', function(data) {
debugger;
console.log("data"); // This never hits
});
If I set breakpoints in peer.js, no data is being received. Nothing changes if I set the connection to reliable. Is there anything else I can try?
I ran into a similar problem and adding a STUN server solved it for me. Also have a look this discussion in the peerjs Google group
peer = new Peer(
{
host: 'localhost',
port: 9000,
debug: true,
config: { 'iceServers': [
{ 'url': 'stun:stun.l.google.com:19302' }
] }
});

How to get the exact IP address of the Restify server on listen?

Consider the following code for rest API node server.
var restify = require('restify');
var server = restify.createServer();
server.get('/echo/:name', function (req, res, next) {
res.send({name: req.params.name});
next();
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
Running up that server with node:
$ node echo.js
restify listening at http://0.0.0.0:8080
It shows 0.0.0.0 which is wrong.
Can anyone the me how to console log the exact IP of the server when its turned on?
Thanks
Update:
On executing the following code I am getting the below mentioned output, which is again makes difficult, which IP to pick?
rest_server.listen(config.appPort, function () {
var adrs = require('os').networkInterfaces();
console.log(adrs);
console.log('%s listening at %s', rest_server.name, rest_server.url);
});
Output:
{ 'Local Area Connection': [ { address: '192.168.3.60', family: 'IPv4', internal
: false } ],
'Loopback Pseudo-Interface 1':
[ { address: '::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
'isatap.TEST.ORG':
[ { address: 'fe80::5efe:c0a8:33c',
family: 'IPv6',
internal: false } ] }
restify listening at http://0.0.0.0:8080
You can set the real address to the listen method, see
http://mcavage.github.io/node-restify/#Server-API and http://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback
server.address() may return the address the server was bound to:
http://nodejs.org/docs/latest/api/net.html#net_server_address
Had the Same issue and figured out the problem, basically you can pass another parameter to the .listen() function and that should be your server IP address
server.listen(port, [host], [backlog], [callback])
server.listen(port, YOUR IP ADDRESS, function(){ });
for you to get your server ip address just do "traceroute www.WEBSITE_URL.com" in the terminal.
let me know if you still have an issue.
thanks
Mahdi
Got some solution, which is as follows.
Any improvements on the same is always welcomed.
var osDetails = require('os');
function getDynamicIP(calbck) {
var ip;
try {
var adrs = osDetails.networkInterfaces();
for (key in adrs) {
if (adrs.hasOwnProperty(key)) {
if (adrs[key][0].internal === false && adrs[key][0].family === 'IPv4') {
ip = adrs[key][0].address;
break;
}
}
}
}
catch (e) {
return calbck(e, null);
}
return calbck(null, ip);
}

Resources