How to get the client ip address from browser in angular (typescript)
Try the services of https://geolocation-db.com to get the public ip address of the user.
import { HttpClient } from "@angular/common/http";
import { catchError, tap } from "rxjs/operators";
this.http.get<any>('https://geolocation-db.com/json/')
.pipe(
catchError(err => {
return throwError(err);
}),
tap(response => {
console.log(response.IPv4);
})
)
Thank you very much, very good solution I took it as a basis for my problem but I did not solve it because it gave me the public IP of the internet server. For an internal network with DHCP, change the URL by the following:
getIpCliente(): Observable<string> {
return this.http.get('http://api.ipify.org/?format=jsonp&callback=JSONP_CALLBACK') // ...using post request '
.map((res:Response) => {console.log('res ', res);
console.log('res.json() ', res.text());
//console.log('parseado ', JSON.parse(res.text()));
console.log('parseado stringify ', JSON.stringify(res.text()));
let ipVar = res.text();
let num = ipVar.indexOf(":");
let num2 = ipVar.indexOf("\"});");
ipVar = ipVar.slice(num+2,num2);
console.log('ipVar -- ',ipVar);
return ipVar}); // ...and calling .json() on the response to return data
//.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
I hope to serve you friends