How to capture ipconfig's ipv4 through javascript? - javascript

In my office, some pc are connected through LAN. And they have allocated with a class A IP address. Now I have created a web application which is running on another server and accesable through LAN pcs. So, I have tried JavaScript code as well as some Java code to get the IP address of pc (which is visible through ipconfig command on that pc itself).
Below JavaScript code I have used to get IP address of LAN pcs:
< script >
var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection)(function() {
var rtc = new RTCPeerConnection({
iceServers: []
});
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', {
reliable: false
});
};
rtc.onicecandidate = function(evt) {
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function(offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function(e) {
console.warn("offer failed", e);
});
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function(k) {
return addrs[k];
});
document.getElementById('list').textContent = displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function(line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})();
else {
document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
} < /script>
For localhost testing, it is giving perfect IPv4 IP address. But when I deploy my code in server, it's started giving something else.
In case of Java: this is my below code:
Enumeration<NetworkInterface> interfaces=NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface current=interfaces.nextElement();
Enumeration<InetAddress> addresses=current.getInetAddresses();
while(addresses.hasMoreElements()){
InetAddress current_addr=addresses.nextElement();
if(current_addr instanceof Inet4Address){
String hostAddr=current_addr.getHostAddress();
String hostName=current_addr.getHostName();
}
}
}
This code also gives me IPv4 of the server in which my web application is deployed.
Please help me to get the IP address of the LAN pc which is visible through 'ipconfig' command on that PC.

I think that Try with this -> https://learn.microsoft.com/en-us/answers/questions/573225/(solved)-how-to-find-the-ip-address-im-using-(ethe

Related

how to send commands to AWS Session manager websocket url using xterm.js?

I have a websocket url created by AWS. URL is created by aws ssm start session using .net sdk.
Start session method gives me streamUrl, token and session ID.
URL is in following format:
wss://ssmmessages.ap-south-1.amazonaws.com/v1/data-channel/sessionidhere?role=publish_subscribe
There is actual session id at placeof "sessionidhere" that I can not share.
I want to open terminal on web using xterm.js. I've read that xterm.js can connect to websocket URL, send messages and receive outputs.
My javascript code is here :
<!doctype html>
<html>
<head>
<link href="~/xterm.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/xterm.js"></script>
</head>
<body>
<div id="terminal"></div>
<script type="text/javascript">
var term = new Terminal({
cursorBlink: "block"
});
var curr_line = "";
var entries = [];
term.open(document.getElementById('terminal'));
const ws = new WebSocket("wss://ssmmessages.ap-south-1.amazonaws.com/v1/data-channel/sessionid?role=publish_subscribe?token=tokenvalue");
var curr_line = "";
var entries = [];
term.write("web shell $ ");
term.prompt = () => {
if (curr_line) {
let data = {
method: "command", command: curr_line
}
ws.send(JSON.stringify(data));
}
};
term.prompt();
ws.onopen = function (e) {
alert("[open] Connection established");
alert("Sending to server");
var enc = new TextEncoder("utf-8"); // always utf-8
// console.log(enc.encode("This is a string converted to a Uint8Array"));
var data = "ls";
console.log(enc.encode(data));
alert(enc.encode(data));
ws.send(enc.encode(data));
alert(JSON.stringify(e));
};
ws.onclose = function (event) {
if (event.wasClean) {
alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
alert('[close] Connection died');
}
};
ws.onerror = function (error) {
alert(`[error] ${error.message}`);
};
// Receive data from socket
ws.onmessage = msg => {
alert(data);
term.write("\r\n" + JSON.parse(msg.data).data);
curr_line = "";
};
term.on("key", function (key, ev) {
//Enter
if (ev.keyCode === 13) {
if (curr_line) {
entries.push(curr_line);
term.write("\r\n");
term.prompt();
}
} else if (ev.keyCode === 8) {
// Backspace
if (curr_line) {
curr_line = curr_line.slice(0, curr_line.length - 1);
term.write("\b \b");
}
} else {
curr_line += key;
term.write(key);
}
});
// paste value
term.on("paste", function (data) {
curr_line += data;
term.write(data);
});
</script>
</body>
</html>
Now, the session is being opened, I am getting alert of connection established. It's being successful connection, but whenever I try to send commands, the connection is being closed by saying 'request to open data channel does not contain a token'. I've tried to send command in 3 ways.
First is :
ws.send("ls")
second:
let data = {
method: "command", command: curr_line
}
ws.send(JSON.stringify(data));
But facing same error i.e. request to open data channel does not contain token, connection died
third:
var enc = new TextEncoder("utf-8");
var data = "ls";
ws.send(enc.encode(data));
For third, I'm not getting any error, but not getting output too... Can someone please help?
The protocol used by AWS Session manager consists of the following :
open a websocket connection on the stream URL
send an authentication request composed of the following JSON stringified :
{
"MessageSchemaVersion": "1.0",
"RequestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"TokenValue": "<YOUR-TOKEN-VALUE>"
}
From this moment the protocol is not JSON anymore. It is implemented in the offical Amazon SSM agent which is required if you want start a SSM session from the AWS CLI. The payload must be sent & receive according this binary format
I had exactly the same requirement as you few months ago so I've made an AWS Session manager client library : https://github.com/bertrandmartel/aws-ssm-session for nodejs and browser. If you want more information about how the protocol works, checkout this
The sample code available for browser use xterm.js
First clone the project and generate websocket URL and token using aws-api with some utility script :
git clone git#github.com:bertrandmartel/aws-ssm-session.git
cd aws-ssm-session
npm i
npm run build
node scripts/generate-session.js
which gives you :
{
SessionId: 'xxxxxx-xxxxxxxxxxxxxx',
TokenValue: 'YOUR_TOKEN',
StreamUrl: 'wss://ssmmessages.eu-west-3.amazonaws.com/v1/data-channel/user-xxxxxxxxxxxxxx?role=publish_subscribe'
}
Then serve the sample app :
npm install http-server -g
http-server -a localhost -p 3000
go to http://localhost:3000/test/web, enter the websocket URI and token :
The sample code for browser :
import { ssm } from "ssm-session";
var socket;
var terminal;
const termOptions = {
rows: 34,
cols: 197
};
function startSession(){
var tokenValue = document.getElementById("tokenValue").value;
var websocketStreamURL = document.getElementById("websocketStreamURL").value;
socket = new WebSocket(websocketStreamURL);
socket.binaryType = "arraybuffer";
initTerminal()
socket.addEventListener('open', function (event) {
ssm.init(socket, {
token: tokenValue,
termOptions: termOptions
});
});
socket.addEventListener('close', function (event) {
console.log("Websocket closed")
});
socket.addEventListener('message', function (event) {
var agentMessage = ssm.decode(event.data);
//console.log(agentMessage);
ssm.sendACK(socket, agentMessage);
if (agentMessage.payloadType === 1){
terminal.write(agentMessage.payload)
} else if (agentMessage.payloadType === 17){
ssm.sendInitMessage(socket, termOptions);
}
});
}
function stopSession(){
if (socket){
socket.close();
}
terminal.dispose()
}
function initTerminal() {
terminal = new window.Terminal(termOptions);
terminal.open(document.getElementById('terminal'));
terminal.onKey(e => {
ssm.sendText(socket, e.key);
});
terminal.on('paste', function(data) {
ssm.sendText(socket, data);
});
}

Find out which Network Interface is which via node or Electron

I use an electron app that needs to send its active IP address (in a LAN) to my server for ongoing communication. For that I use a brilliant script I found here which works great:
function getIPs() {
let ifaces = os.networkInterfaces();
console.log(ifaces);
let ipAdresse = '';
Object.keys(ifaces).forEach(function (ifname) {
let alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
return;
}
if (alias >= 1) {
console.log(ifname + ':' + alias, iface.address);
} else {
console.log(ifname, iface.address);
ipAdress = iface.address;
}
++alias;
});
});
return ipAdress;
}
The Problem I have is: if this Client is connected to more then one Network (sometimes the users connect to a WIFI as well to have internet), I cannot tell which one is my LAN and which belongs to the WIFI. As I have no Control over the used WIFI I cannot tell them apart by their IP-Range.
Is there a way to tell (in Node or Electron) if an Network Interface belongs to Cable or WIFI?

How to Get The List of IP Addresses of All PCs Connected in same network (wifi) in javascript?

using this code i can find ip of my system but i want to get all the ip and name of the device connect in the network. i cant use any server side programming language like php c# as i need to operate the full system locally. Please help.
<!doctype html>
<html><head>
<meta charset="utf-8">
<title>Network IP Address via ipcalf.com</title>
</head><body>
Your network IP is: <h1 id=list>-</h1> Make the locals proud.
<script>
// NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({iceServers:[]});
if (1 || window.mozRTCPeerConnection) { // FF [and now Chrome!] needs a channel/stream to proceed
rtc.createDataChannel('', {reliable:false});
};
rtc.onicecandidate = function (evt) {
// convert the candidate to SDP so we can run it through our general parser
// see https://twitter.com/lancestout/status/525796175425720320 for details
if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
document.getElementById('list').textContent = displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
if (~line.indexOf("a=candidate")) { // http://tools.ietf.org/html/rfc4566#section-5.13
var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) { // http://tools.ietf.org/html/rfc4566#section-5.7
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})();
else {
document.getElementById('list').innerHTML = "<code>ifconfig | grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
</script>
</body></html>
You can't. This isn't something that is available in general -- devices on the local network are not guaranteed to advertise themselves on the network, and may not have names at all -- and it is certainly not available to Javascript running in a browser.

Get current IP in JS (no third party services) [duplicate]

This question already has answers here:
How to get client's IP address using JavaScript? [closed]
(31 answers)
Closed 6 years ago.
Is posible Get Client IP Using WebRTC JS API and the ICE protocol (STUN for public IP)?
Yes you can, using WebRTC JS API and the ICE protocol (STUN for public IP).
More info here.
//get the IP addresses associated with an account
function getIPs(callback){
var ip_dups = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
//bypass naive webrtc blocking using an iframe
if(!RTCPeerConnection){
//NOTE: you need to have an iframe in the page right above the script tag
//
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
//<script>...getIPs called in here...
//
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate){
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];
//remove duplicates
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}
//listen for candidate events
pc.onicecandidate = function(ice){
//skip non-candidate events
if(ice.candidate)
handleCandidate(ice.candidate.candidate);
};
//create a bogus data channel
pc.createDataChannel("");
//create an offer sdp
pc.createOffer(function(result){
//trigger the stun server request
pc.setLocalDescription(result, function(){}, function(){});
}, function(){});
//wait for a while to let everything done
setTimeout(function(){
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
//Test: Print the IP addresses into the console
getIPs(function(ip){console.log(ip);});

XMPP web client (using strophe.js) taking time to connect with ejabberd server

I have implemented an XMPP client for JavaScript (using strophe.js), for which I am referring to the book Professional XMPP with JavaScript and jQuery by Jack Moffitt.
The book has a great explanation on working of XMPP JavaScript client using "strophe.js".
With my code, the XMPP web client is taking 6 seconds to connect with the XMPP server (ejabberd using BOSH), which is not desirable for my application.
Can some one explain why this is happening?
My XMPP client code is as below:
var Arthur = {
connection: null,
jid:"20147001#localhost",
password: "XXXX2014",
handle_message: function (message) {
if ($(message).attr('from')) {
if($(message).attr('from').match(/^abcd007#localhost/)){
console.log("inside message received");
var body = $(message).find('body').contents();
var span = $("<span></span>");
body.each(function () {
if (document.importNode) {
$(document.importNode(this, true)).appendTo(span);
console.log(span);
console.log(span.text());
}
});
notiReceived(span.text());
console.log("afte notiReceived executed");
}
if($(message).attr('from').match(/^xyz2014#localhost/)){
console.log("inside message received");
var body1 = $(message).find('body').contents();
var span1 = $("<span></span>");
body1.each(function () {
if (document.importNode) {
$(document.importNode(this, true)).appendTo(span1);
//console.log(span.find('text'));
console.log(span1);
console.log(span1.text());
}
});
notiReceived(span1.text());
console.log("afte notiReceived executed");
}
}
return true;
}
};
function sendPushNotification(to,operation,request_id,message){
if(to=="citizen"){
var myObject = new Object();
myObject.FROM="Executive";
myObject.FUNCTION=operation;
myObject.MESSAGE = message;
myObject.REQUESTID= request_id;
console.log("inside citizen::"+myObject);
var myString = JSON.stringify(myObject);
$(this).val('');
var msg = $msg({to: 'abcd007#localhost', type: 'chat'})
.c('body').t(myString);
console.log("inside keypress data is::"+msg);
Arthur.connection.send(msg);
}
if(to=="technician"){
var myObject1 = new Object();
myObject1.FROM="Executive";
myObject1.FUNCTION=operation;
myObject1.MESSAGE = "Check Request Status";
myObject1.REQUESTID= request_id;
console.log("inside technician:"+myObject1);
var myString1 = JSON.stringify(myObject1);
$(this).val('');
var msg1 = $msg({to: 'xyz2014#localhost', type: 'chat'})
.c('body').t(myString1);
console.log("after msg send to technician"+msg1);
Arthur.connection.send(msg1);
}
};
function connected() {
console.log("inside connected");
Arthur.connection.addHandler(Arthur.handle_message,
null, "message", "chat");
console.log("inside connected");
Arthur.connection.send($pres());
};
function disconnected() {
console.log("disconnected");
Arthur.connection = null;
};
function disconnect(){
Arthur.connection.disconnect();
};
function connectXMPP() {
var conn = new Strophe.Connection(
hosturl.URL+":5280/http-bind");
console.log("inside connection");
conn.connect(Arthur.jid, Arthur.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
connected();
console.log("connected");
} else if (status === Strophe.Status.DISCONNECTED) {
disconnected();
}
});
Arthur.connection = conn;
};
I don't know whether this is the case here, but in general when connections take long to established, the cause is often a host name resolution issue.
For instance, if a host has both an IPv4 and IPv6 address, but there is no IPv6 connectivity yet IPv6 is tried first, then you may get a delay until the IPv6 connection attempt has timed out.
To examine whether domain name resolution is the cause, you might want to take a look at the network traffic using a tool such as Wireshark.

Categories