socket.remoteAddress returning ::1? [duplicate] - javascript

I was playing with sockets on local machine with no network connection. See below:
IPAddress address = IPAddress.Any; // doesn't work
IPAddress address = IPAddress.Parse("::1"); // works
So what is exactly ::1 IP address ? Is it the default available IP address or it's the loopback address ? what happens to above code (working line) on a machine with dedicated IP address and network connection ?
EDIT:
exact code is used to bind a specific IP address to socket. Here it is:
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
// here's the bind delegate:
private IPEndPoint Bind(ServicePoint sp, IPEndPoint ep, int retryCount)
{
return new IPEndPoint(IPAddress.Parse("::1"), 0);
}

::1 is the loopback address in IPv6. Think of it as the IPv6 version of 127.0.0.1.
See http://en.wikipedia.org/wiki/Localhost

Just to add little more info to it, in IPv6 loopback address is represented as 127 zeroes followed by a 1 i.e (0000... 127 times..1).
It's representation should have been like this -> 0000:0000:0000:0000:0000:0000:0000:0001 but we have some short form representation for this. If there are all zeroes in a single block you can replace it by single 0. So it becomes -> 0:0:0:0:0:0:0:0001.
Again we can see that we have runs of zeroes, they can be eliminated and we get
-> ::0001 -> ::1 .

The simple answer is that:
::1 is the compressed format of IPV6 loopback address 0:0:0:0:0:0:0:1. It is the equivalent of the IPV4 address 127.0. 0.1

Related

Delete USB history (regedit) with script

I have a javascript and Powershell script allowing to detect a usb plug, and which shows me a pop up. Indeed, my script only detects new usb keys that have not yet been plugged into the system. That's why I would like to delete the usb key history from my computer, like USB OBLIVION does, in order to have as a new connection to each usb plug.
I don't see what I need to add to my script... I have already tried deleting the content of:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceClasses\
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB
Thanks
You could try these, but don't forget to wipe the from them other 3 paths as well
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\SWD\WPDBUSENUM
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Portable Devices\Devices\
You could also consider using WMI Event subscriptions, this works whatever the usb key is already known or not, but do not clear the registry :
to detect usb plug :
Register-CIMIndicationEvent –Query `
"Select * From __InstanceCreationEvent Within 1 Where TargetInstance IsA 'Win32_LogicalDisk'" `
–SourceIdentifier "WMIInsert" –Action { Write-Host `
"$($Event.SourceEventArgs.NewEvent.TargetInstance.Name) plugged!`n" }
to detect usb ejection :
Register-CIMIndicationEvent –Query `
"Select * From __InstanceDeletionEvent Within 1 Where TargetInstance IsA 'Win32_LogicalDisk'" `
–SourceIdentifier "WMIEject" –Action { Write-Host `
"$($Event.SourceEventArgs.NewEvent.TargetInstance.Name) ejected!`n" }
Within 1 means to detect every one second. Depending on your needs, you can configure Within 30 for example to look it for every 30 seconds (every plug or ejection in the meantime are captured as well).
the -Action parameter let you do whatever you want since this is a scriptblock (In the example I provided the event is only displayed to the console).
And do not forget that StackOverflow is not a free coding service, so next time, please share the piece of code where you have got a problem or a bug.

Check local (internal) IP with JavaScript

I know that this will seem like a duplicate, but I honestly have not been able to find any answer that solves this.
I have two iPads set up with static IP addresses on a network that can only access www.example.com (network restriction, not iPad restriction). example.com is an eCommerce site and I want to fill in a coupon field whenever either of these two iPads visit the site.
The only way I can think of doing this is getting the local IP addresses of the iPads (e.g. 192.168.0.x) and creating a whitelist array. But my problem is trying to detect the browsing device's local IP.
I cannot use any resources outside of the example.com domain and I can't use the network's public IP as there will be lots of other devices connected.
Also, I've tried WebRTC but it's Chrome and Firefox only, and I am limited to the iPad's native Safari browser.
Help me Overflow Kenobi, you're my only hope!
EDIT
Conditions have changed. I found out that no other devices will be using the checkout service, so I can now target the external IP. Details about how I did this are below.
OK, I've found a solution to my problem.
One correction first to my original question:
I just found out that none of the other devices on the network will actually be used for purchasing on the website, so the iPads are the only two devices that will enter the checkout.
Knowing this now, I am able to target the public IP of the network. I've done this using two scripts, one in an external PHP file (our server isn't setup to run PHP in HTML files) and one in an external JavaScript file (easier management as there are multiple versions of the checkout page, so if I need to change the discount code I just have to update the JS file.)
PHP file:
// Declare content as JavaScript
Header("content-type: application/x-javascript");
// Declare variables for IP adress requests
$http_client_ip = $_SERVER['HTTP_CLIENT_IP'];
$http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_addr = $_SERVER['REMOTE_ADDR'];
// Request for most accurate IP address
if (!empty($http_client_ip)) {
$ip_address = $http_client_ip;
} else if (!empty($http_x_forwarded_for)) {
$ip_address = $http_x_forwarded_for;
} else {
$ip_address = $remote_addr;
}
// Add results to array - multiple IP addresses may be returned
$list = explode(',', $ip_address, 2);
// Write the first IP address in array as JavaScript
echo 'document.write(\'<div class="myIP" style="display:none;">' . $list[0] . '</div>\')';
JS file:
// Array of allowed IP addresses
var allowedIP = ['x.x.x.x'];
// Coupon code
var couponCode = "CODE001";
// Run script when page is loaded
$(document).ready(function () {
// Get device IP from 'myIP' div loaded by php
var ipAddress = $('.myIP').text();
// Check if device IP matches any of the IPs in the Allowed array
for (var i = 0; i<allowedIP.length;i++) {
if (ipAddress == allowedIP[i]) {
// If it matches, write to console
console.log("Your external IP is allowed");
// Add coupon code to input field
$('input[name="coupon"]').val(couponCode);
} else {
// If it does not match, write to console
console.log("Sorry buddy, you're not on the list.");
}
};
});

Get Machine name or any unique code with php

I want to get user machine name or any unique code instead of IP.
Two system on same network have same IP but I want unique Code/number/name of each System.
Please tell me How can I do this with php.
Thanks
EDITED......
I am using below code. This is working on localend. But this stop working on live server. May be its getting server mac address but I want local machine Mac address from where my web app is accessing.
ob_start();//Get the ipconfig details using system commond
system('ipconfig /all');
// Capture the output into a variable
$mycom=ob_get_contents();
// Clean (erase) the output buffer
ob_clean();
$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);
// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo '<h1>demo---> '.$mac.'</h1>';
Edited
If this is not possible in php then javascript can be used for this? How can I use javascript to get client machine Physical Address....
You should try the below code.
$ip = $_SERVER['REMOTE_ADDR'];
// don't miss to use escapeshellarg(). Make it impossible to inject shell code
$mac1 = shell_exec('arp -a ' . escapeshellarg($ip));
// can be that the IP doesn't exist or the host isn't up (spoofed?)
// check if we found an address
if(empty($mac1)) {
die("No mac address for $ip not found");
}
// having it
echo "mac address for $ip: $mac1";
Hope this will work for you.

Get LAN IP address from USB tethering network from javascript

I know it sound crazy but I need it.
I found code that gets the public IP address:
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
} </script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
But that code can't help me here. I do even know if this is possible. But I am looking for the 192.168.42.123 address. How can I found this IP from javascript ?
$ ifconfig
usb0 Link encap:Ethernet HWaddr 6b:fe:56:15:6b:33
inet addr:192.168.42.123 Bcast:192.168.42.255 Mask:255.255.255.0
inet6 addr: fe80::68fe:96ff:fe15:6b49/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1802 errors:0 dropped:0 overruns:0 frame:0
TX packets:2041 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1513563 (1.5 MB) TX bytes:318292 (318.2 KB)
You can't. Whenever he's running your script, the user is on the public network (Internet), and therefore the IP address you'll get through javascript will always be the public one. But you may be taking the problem from the wrong side and doesn't actually need this IP address... there's nothing in it that a remote user could use...

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible?
Edit: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>
Yay, no server proxies needed.
Pure JS can't. If you have a server script under the same domain that prints it out you could send a XMLHttpRequest to read it.
I know this question was asked a very long time ago, but I figured I'd offer a more recent answer.
DNS over HTTPS (DoH)
You can send DNS queries over HTTPS to DNS resolvers that support it. The standard for DOH is described in RFC 8484.
This is a similar thing to what all the other answers suggest, only that DoH is actually the DNS protocol over HTTPS. It's also a "proposed" Internet standard and it's becoming quite popular. For example, some major browsers either support it or have plans to support it (Chrome, Edge, Firefox), and Microsoft is in the process of building it into their operating system.
One of the purposes of DoH is:
allowing web applications to access DNS information via existing browser APIs in a safe way consistent with Cross Origin Resource Sharing (CORS)
There's an open source tool made especially for doing DNS lookups from web applications called dohjs. It does DNS over HTTPS (DoH) wireformat queries as described in RFC 8484. It supports both GET and POST methods.
Full disclosure: I am a contributor to dohjs.
Another JavaScript library with similar features is found here - https://github.com/sc0Vu/doh-js-client. I haven't used this one personally, but I think it would work client side as well.
DNS over HTTPS JSON APIs
If you don't want to bother with DNS wireformat, both Google and Cloudflare offer JSON APIs for DNS over HTTPS.
Google's JSON API
Doc: https://developers.google.com/speed/public-dns/docs/doh/json
Endpoint: https://dns.google/resolve?
Cloudflare's JSON API
Doc: https://developers.cloudflare.com/1.1.1.1/dns-over-https/json-format/
Endpoint https://cloudflare-dns.com/dns-query?
Example Javascript code to lookup example.com with Google's JSON DOH API:
var response = await fetch('https://dns.google/resolve?name=example.com');
var json = await response.json();
console.log(json);
Examples from the RFC for DOH GET and POST with wireformat
Here are the examples the RFC gives for both GET and POST (see https://www.rfc-editor.org/rfc/rfc8484#section-4.1.1):
GET example:
The first example request uses GET to request "www.example.com".
:method = GET
:scheme = https
:authority = dnsserver.example.net
:path = /dns-query?dns=AAABAAABAAAAAAAAA3d3dwdleGFtcGxlA2NvbQAAAQAB
accept = application/dns-message
POST example:
The same DNS query for "www.example.com", using the POST method would
be:
:method = POST
:scheme = https
:authority = dnsserver.example.net
:path = /dns-query
accept = application/dns-message
content-type = application/dns-message
content-length = 33
<33 bytes represented by the following hex encoding>
00 00 01 00 00 01 00 00 00 00 00 00 03 77 77 77
07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 00 01 00
01
Other places to send DOH queries
You can find a list of some public DNS resolvers that support DNS over HTTPS in a couple places:
DNSCrypt has a long list of public DoH and DNSCrypt resolver on their Github, and a nice interactive version of the list at https://dnscrypt.info/public-servers/
Wikipedia - comparison of public recursive nameservers
List on Curl's wiki
(short) list on dnsprivacy.org
Of the above resources, I'd say that the list on Curl's wiki and the DNSCrypt list are are probably the most complete and the most frequently updated. Curl's page also includes a list of open source tools for DoH (servers, proxies, client libs, etc).
There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you.
I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript.
Very late, but I guess many people will still land here through "Google Airlines". A moderm approach is to use WebRTC that doesn't require server support.
https://hacking.ventures/local-ip-discovery-with-html5-webrtc-security-and-privacy-risk/
Next code is a copy&paste from http://net.ipcalf.com/
// 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 (window.mozRTCPeerConnection) { // FF needs a channel/stream to proceed
rtc.createDataChannel('', {reliable:false});
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP(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.";
}
The hosted JSONP version works like a charm, but it seems it goes over its resources during night time most days (Eastern Time), so I had to create my own version.
This is how I accomplished it with PHP:
<?php
header('content-type: application/json; charset=utf-8');
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['callback'] . '(' . $data . ');';
?>
Then the Javascript is exactly the same as before, just not an array:
<script type="application/javascript">
function getip(ip){
alert('IP Address: ' + ip);
}
</script>
<script type="application/javascript" src="http://www.anotherdomain.com/file.php?callback=getip"> </script>
Simple as that!
Side note: Be sure to clean your $_GET if you're using this in any public-facing environment!
There's a third-party service which provides a CORS-friendly REST API to perform DNS lookups from the browser - https://exana.io/tools/dns/
I am aware this is an old question but my solution may assist others.
I find that the JSON(P) services which make this easy do not last forever but the following JavaScript works well for me at the time of writing.
<script type="text/javascript">function z (x){ document.getElementById('y').innerHTML=x.query }</script>
<script type='text/javascript' src='http://ip-api.com/json/zero.eu.org?callback=z'></script>
The above writes my server's IP on the page it is located but the script can be modified to find any IP by changing 'zero.eu.org' to another domain name.
This can be seen in action on my page at: http://meon.zero.eu.org/
There is a javascript library DNS-JS.com that does just this.
DNS.Query("dns-js.com",
DNS.QueryType.A,
function(data) {
console.log(data);
});
As many people said you need to use an external service and call it. And that will only get you the DNS resolution from the server perspective.
If that's good enough and if you just need DNS resolution you can use the following Docker container:
https://github.com/kuralabs/docker-webaiodns
Endpoints:
[GET] /ipv6/[domain]:
Perform a DNS resolution for given domain and return the associated IPv6
addresses.
{
"addresses": [
"2a01:91ff::f03c:7e01:51bd:fe1f"
]
}
[GET] /ipv4/[domain]:
Perform a DNS resolution for given domain and return the associated IPv4
addresses.
{
"addresses": [
"139.180.232.162"
]
}
My recommendation is that you setup your web server to reverse proxy to the container on a particular endpoint in your server serving your Javascript and call it using your standard Javascript Ajax functions.
Doing this would require to break the browser sandbox. Try to let your server do the lookup and request that from the client side via XmlHttp.
Firefox has a built-in API for this since v60, for WebExtensions:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve
sure you can do that without using any addition, just pure javascript, by using this method of dns browser.dns.resolve("example.com");
but it is compatible just with FIREFOX 60 you can see more information on MDN https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve
I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.
Maybe I missed the point but in reply to NAVY guy here is how the browser can tell you the 'requestor's' IP address (albeit maybe only their service provider).
Place a script tag in the page to be rendered by the client that calls (has src pointing to) another server that is not loaded balanced (I realize that this means you need access to a 2nd server but hosting is cheap these days and you can set this up easily and cheaply).
This is the kind of code that needs to be added to client page:
On the other server "someServerIown" you need to have the ASP, ASPX or PHP page that;
----- contains server code like this:
"<%
Response.Write("var clientipaddress = '" & Request.ServerVariables("REMOTE_ADDR") & "';")
%>"
(without the outside dbl quotes :-))
---- and writes this code back to script tag:
var clientipaddress = '178.32.21.45';
This effectively creates a Javascript variable that you can access with Javascript on the page no less.
Hopefully, you access this var and write the value to a form control ready for sending back.
When the user posts or gets on the next request your Javascript and/or form sends the value of the variable that the "otherServerIown" has filled in for you, back to the server you would like it on.
This is how I get around the dumb load balancer we have that masks the client IP address and makes it appear as that of the Load balancer .... dumb ... dumb dumb dumb!
I haven't given the exact solution because everyone's situation is a little different. The concept is sound, however. Also, note if you are doing this on an HTTPS page your "otherServerIOwn" must also deliver in that secure form otherwise Client is alerted to mixed content. And if you do have https then make sure ALL your certs are valid otherwise client also gets a warning.
Hope it helps someone! Sorry, it took a year to answer/contribute. :-)
My version is like this:
php on my server:
<?php
header('content-type: application/json; charset=utf-8');
$data = json_encode($_SERVER['REMOTE_ADDR']);
$callback = filter_input(INPUT_GET,
'callback',
FILTER_SANITIZE_STRING,
FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
echo $callback . '(' . $data . ');';
?>
jQuery on the page:
var self = this;
$.ajax({
url: this.url + "getip.php",
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}).done( function( json ) {
self.ip = json;
});
It works cross domain.
It could use a status check. Working on that.
If the client has Java installed, you could do something like this:
ipAddress = java.net.InetAddress.getLocalHost().getHostAddress();
Other than that, you will probably have to use a server side script.

Categories

Resources