Is it possible to get the IP address of the device using some code?
This is my helper util to read IP and MAC addresses. Implementation is pure-java, but I have a comment block in getMACAddress() which could read the value from the special Linux(Android) file. I've run this code only on few devices and Emulator but let me know here if you find weird results.
// AndroidManifest.xml permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// test functions
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
Utils.java
import java.io.*;
import java.net.*;
import java.util.*;
//import org.apache.http.conn.util.InetAddressUtils;
public class Utils {
/**
* Convert byte array to hex string
* #param bytes toConvert
* #return hexValue
*/
public static String bytesToHex(byte[] bytes) {
StringBuilder sbuf = new StringBuilder();
for(int idx=0; idx < bytes.length; idx++) {
int intVal = bytes[idx] & 0xff;
if (intVal < 0x10) sbuf.append("0");
sbuf.append(Integer.toHexString(intVal).toUpperCase());
}
return sbuf.toString();
}
/**
* Get utf8 byte array.
* #param str which to be converted
* #return array of NULL if error was found
*/
public static byte[] getUTF8Bytes(String str) {
try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
}
/**
* Load UTF8withBOM or any ansi text file.
* #param filename which to be converted to string
* #return String value of File
* #throws java.io.IOException if error occurs
*/
public static String loadFileAsString(String filename) throws java.io.IOException {
final int BUFLEN=1024;
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
byte[] bytes = new byte[BUFLEN];
boolean isUTF8=false;
int read,count=0;
while((read=is.read(bytes)) != -1) {
if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
isUTF8=true;
baos.write(bytes, 3, read-3); // drop UTF8 bom marker
} else {
baos.write(bytes, 0, read);
}
count+=read;
}
return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
} finally {
try{ is.close(); } catch(Exception ignored){}
}
}
/**
* Returns MAC address of the given interface name.
* #param interfaceName eth0, wlan0 or NULL=use first interface
* #return mac address or empty string
*/
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null) return "";
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) buf.append(String.format("%02X:",aMac));
if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
return buf.toString();
}
} catch (Exception ignored) { } // for now eat exceptions
return "";
/*try {
// this is so Linux hack
return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
} catch (IOException ex) {
return null;
}*/
}
/**
* Get IP address from first non-localhost interface
* #param useIPv4 true=return ipv4, false=return ipv6
* #return address or empty string
*/
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
} catch (Exception ignored) { } // for now eat exceptions
return "";
}
}
Disclaimer: Ideas and example code to this Utils class came from
several SO posts and Google. I have cleaned and merged all examples.
With permission ACCESS_WIFI_STATE declared in AndroidManifest.xml:
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"/>
One can use the WifiManager to obtain the IP address:
Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
I've added inetAddress instanceof Inet4Address to check if it is a ipv4 address.
I used following code:
The reason I used hashCode was because I was getting some garbage values appended to the ip address when I used getHostAddress . But hashCode worked really well for me as then I can use Formatter to get the ip address with correct formatting.
Here is the example output :
1.using getHostAddress : ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
2.using hashCode and Formatter : ***** IP=238.194.77.212
As you can see 2nd methods gives me exactly what I need.
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i(TAG, "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
Though there's a correct answer, I share my answer here and hope that this way will more convenience.
WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
Below code might help you.. Don't forget to add permissions..
public String getLocalIpAddress(){
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Add below permission in the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
happy coding!!
kotlin minimalist version
fun getIpv4HostAddress(): String {
NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
networkInterface.inetAddresses?.toList()?.find {
!it.isLoopbackAddress && it is Inet4Address
}?.let { return it.hostAddress }
}
return ""
}
You do not need to add permissions like what is the case with the solutions provided so far. Download this website as a string:
http://www.ip-api.com/json
or
http://www.telize.com/geoip
Downloading a website as a string can be done with java code:
http://www.itcuties.com/java/read-url-to-string/
Parse the JSON object like this:
https://stackoverflow.com/a/18998203/1987258
The json attribute "query" or "ip" contains the IP address.
private InetAddress getLocalAddress()throws IOException {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
//return inetAddress.getHostAddress().toString();
return inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return null;
}
Method getDeviceIpAddress returns device's ip address and prefers wifi interface address if it connected.
#NonNull
private String getDeviceIpAddress() {
String actualConnectedToNetwork = null;
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connManager != null) {
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
actualConnectedToNetwork = getWifiIp();
}
}
if (TextUtils.isEmpty(actualConnectedToNetwork)) {
actualConnectedToNetwork = getNetworkInterfaceIpAddress();
}
if (TextUtils.isEmpty(actualConnectedToNetwork)) {
actualConnectedToNetwork = "127.0.0.1";
}
return actualConnectedToNetwork;
}
#Nullable
private String getWifiIp() {
final WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (mWifiManager != null && mWifiManager.isWifiEnabled()) {
int ip = mWifiManager.getConnectionInfo().getIpAddress();
return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "."
+ ((ip >> 24) & 0xFF);
}
return null;
}
#Nullable
public String getNetworkInterfaceIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface networkInterface = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
String host = inetAddress.getHostAddress();
if (!TextUtils.isEmpty(host)) {
return host;
}
}
}
}
} catch (Exception ex) {
Log.e("IP Address", "getLocalIpAddress", ex);
}
return null;
}
In your activity, the following function getIpAddress(context) returns the phone's IP address:
public static String getIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(WIFI_SERVICE);
String ipAddress = intToInetAddress(wifiManager.getDhcpInfo().ipAddress).toString();
ipAddress = ipAddress.substring(1);
return ipAddress;
}
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
This is a rework of this answer which strips out irrelevant information, adds helpful comments, names variables more clearly, and improves the logic.
Don't forget to include the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
InternetHelper.java:
public class InternetHelper {
/**
* Get IP address from first non-localhost interface
*
* #param useIPv4 true=return ipv4, false=return ipv6
* #return address or empty string
*/
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface interface_ : interfaces) {
for (InetAddress inetAddress :
Collections.list(interface_.getInetAddresses())) {
/* a loopback address would be something like 127.0.0.1 (the device
itself). we want to return the first non-loopback address. */
if (!inetAddress.isLoopbackAddress()) {
String ipAddr = inetAddress.getHostAddress();
boolean isIPv4 = ipAddr.indexOf(':') < 0;
if (isIPv4 && !useIPv4) {
continue;
}
if (useIPv4 && !isIPv4) {
int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
ipAddr = delim < 0 ? ipAddr.toUpperCase() :
ipAddr.substring(0, delim).toUpperCase();
}
return ipAddr;
}
}
}
} catch (Exception ignored) { } // if we can't connect, just return empty string
return "";
}
/**
* Get IPv4 address from first non-localhost interface
*
* #return address or empty string
*/
public static String getIPAddress() {
return getIPAddress(true);
}
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString();
public static String getdeviceIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
You can use LinkProperties. It's recommended for new Android versions.
This function retrieves local IP address for both WiFi and Mobile Data. It requires Manifest.permission.ACCESS_NETWORK_STATE permission.
#Nullable
public static String getDeviceIpAddress(#NonNull ConnectivityManager connectivityManager) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork());
InetAddress inetAddress;
for(LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
inetAddress = linkAddress.getAddress();
if (inetAddress instanceof Inet4Address
&& !inetAddress.isLoopbackAddress()
&& inetAddress.isSiteLocalAddress()) {
return inetAddress.getHostAddress();
}
}
return null;
}
Recently, an IP address is still returned by getLocalIpAddress() despite being disconnected from the network (no service indicator). It means the IP address displayed in the Settings> About phone> Status was different from what the application thought.
I have implemented a workaround by adding this code before:
ConnectivityManager cm = getConnectivityManager();
NetworkInfo net = cm.getActiveNetworkInfo();
if ((null == net) || !net.isConnectedOrConnecting()) {
return null;
}
Does that ring a bell to anyone?
Simply use Volley to get the ip from this site
RequestQueue queue = Volley.newRequestQueue(this);
String urlip = "http://checkip.amazonaws.com/";
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlip, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
txtIP.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtIP.setText("didnt work");
}
});
queue.add(stringRequest);
in Kotlin, without Formatter
private fun getIPAddress(useIPv4 : Boolean): String {
try {
var interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
var addrs = Collections.list(intf.getInetAddresses());
for (addr in addrs) {
if (!addr.isLoopbackAddress()) {
var sAddr = addr.getHostAddress();
var isIPv4: Boolean
isIPv4 = sAddr.indexOf(':')<0
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
var delim = sAddr.indexOf('%') // drop ip6 zone suffix
if (delim < 0) {
return sAddr.toUpperCase()
}
else {
return sAddr.substring(0, delim).toUpperCase()
}
}
}
}
}
}
} catch (e: java.lang.Exception) { }
return ""
}
A device might have several IP addresses, and the one in use in a particular app might not be the IP that servers receiving the request will see. Indeed, some users use a VPN or a proxy such as Cloudflare Warp.
If your purpose is to get the IP address as shown by servers that receive requests from your device, then the best is to query an IP geolocation service such as Ipregistry (disclaimer: I work for the company) with its Java client:
https://github.com/ipregistry/ipregistry-java
IpregistryClient client = new IpregistryClient("tryout");
RequesterIpInfo requesterIpInfo = client.lookup();
requesterIpInfo.getIp();
In addition to being really simple to use, you get additional information such as country, language, currency, the time zone for the device IP and you can identify whether the user is using a proxy.
This is the easiest and simple way ever exist on the internet...
First of all, add this permission to your manifest file...
"INTERNET"
"ACCESS_NETWORK_STATE"
add this in onCreate file of Activity..
getPublicIP();
Now Add this function to your MainActivity.class.
private void getPublicIP() {
ArrayList<String> urls=new ArrayList<String>(); //to read each line
new Thread(new Runnable(){
public void run(){
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("https://api.ipify.org/"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
PermissionsActivity.this.runOnUiThread(new Runnable(){
public void run(){
try {
Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
Here is kotlin version of #Nilesh and #anargund
fun getIpAddress(): String {
var ip = ""
try {
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
ip = Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
} catch (e: java.lang.Exception) {
}
if (ip.isEmpty()) {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val networkInterface = en.nextElement()
val enumIpAddr = networkInterface.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
val host = inetAddress.getHostAddress()
if (host.isNotEmpty()) {
ip = host
break;
}
}
}
}
} catch (e: java.lang.Exception) {
}
}
if (ip.isEmpty())
ip = "127.0.0.1"
return ip
}
Compiling some of the ideas to get the wifi ip from the WifiManager in a nicer kotlin solution:
private fun getWifiIp(context: Context): String? {
return context.getSystemService<WifiManager>().let {
when {
it == null -> "No wifi available"
!it.isWifiEnabled -> "Wifi is disabled"
it.connectionInfo == null -> "Wifi not connected"
else -> {
val ip = it.connectionInfo.ipAddress
((ip and 0xFF).toString() + "." + (ip shr 8 and 0xFF) + "." + (ip shr 16 and 0xFF) + "." + (ip shr 24 and 0xFF))
}
}
}
}
Alternatively you can get the ip adresses of ip4 loopback devices via the NetworkInterface:
fun getNetworkIp4LoopbackIps(): Map<String, String> = try {
NetworkInterface.getNetworkInterfaces()
.asSequence()
.associate { it.displayName to it.ip4LoopbackIps() }
.filterValues { it.isNotEmpty() }
} catch (ex: Exception) {
emptyMap()
}
private fun NetworkInterface.ip4LoopbackIps() =
inetAddresses.asSequence()
.filter { !it.isLoopbackAddress && it is Inet4Address }
.map { it.hostAddress }
.filter { it.isNotEmpty() }
.joinToString()
Blockquote
// get Device Ip Address
open fun getLocalIpAddress(): String? {
try {
val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val networkInterface: NetworkInterface = en.nextElement()
val enumerationIpAddress: Enumeration<InetAddress> = networkInterface.inetAddresses
while (enumerationIpAddress.hasMoreElements()) {
val inetAddress: InetAddress = enumerationIpAddress.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return inetAddress.getHostAddress()
}
}
}
} catch (ex: SocketException) {
ex.printStackTrace()
}
return null
}
If you have a shell ; ifconfig eth0 worked for x86 device too
Please check this code...Using this code. we will get ip from mobile internet...
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
I don't do Android, but I'd tackle this in a totally different way.
Send a query to Google, something like:
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=my%20ip
And refer to the HTML field where the response is posted. You may also query directly to the source.
Google will most like be there for longer than your Application.
Just remember, it could be that your user does not have internet at this time, what would you like to happen !
Good Luck
You can do this
String stringUrl = "https://ipinfo.io/ip";
//String stringUrl = "http://whatismyip.akamai.com/";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.instance);
//String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, stringUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.e(MGLogTag, "GET IP : " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
IP = "That didn't work!";
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
// #NonNull
public static String getIPAddress() {
if (TextUtils.isEmpty(deviceIpAddress))
new PublicIPAddress().execute();
return deviceIpAddress;
}
public static String deviceIpAddress = "";
public static class PublicIPAddress extends AsyncTask<String, Void, String> {
InetAddress localhost = null;
protected String doInBackground(String... urls) {
try {
localhost = InetAddress.getLocalHost();
URL url_name = new URL("http://bot.whatismyipaddress.com");
BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
deviceIpAddress = sc.readLine().trim();
} catch (Exception e) {
deviceIpAddress = "";
}
return deviceIpAddress;
}
protected void onPostExecute(String string) {
Lg.d("deviceIpAddress", string);
}
}
In all honesty I am only a little familiar with code safety, so this may be hack-ish. But for me this is the most versatile way to do it:
package com.my_objects.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyIpByHost
{
public static void main(String a[])
{
try
{
InetAddress host = InetAddress.getByName("nameOfDevice or webAddress");
System.out.println(host.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
} }
For kotlin language.
fun contextIP(context: Context): String {
val wm: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
return Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
}
Related
I'm creating a java project that shows hostname , ip and mac address of connected devices using java . I use InetAddress but it only shows me the Ip's and hostname of connected computers without MAC and also can't see connected mobiles like Android devices.
I tried almost every solution on StackOverFlow but none of theme seems to work
public class HostDiscovery
{
private String address;
private int discoveryTimeout;
HostDiscovery( String address, int discoveryTimeout)
{
this.address = address;
this.discoveryTimeout = discoveryTimeout;
}
public Future<HostDiscoveryResult> multithreadedHostDicovery(final ExecutorService exService){
return exService.submit(() -> {
try
{
String HostName = null;
String MacAddress = null;
boolean result = InetAddress.getByName(address).isReachable(discoveryTimeout);
InetAddress ip = InetAddress.getByName(address);
if (result)
{
HostName = InetAddress.getByName(address).getHostName();
if(HostName.endsWith(".mshome.net")){
HostName = HostName.replaceAll(".mshome.net", "");
}
MacAddress = getMacAddress(ip);
}
return new HostDiscoveryResult(address, result, HostName, MacAddress);
} catch (SocketException ex)
{
return new HostDiscoveryResult(address, false, null, null);
}
});
}
private static String getMacAddress(InetAddress ip) throws UnknownHostException {
String address = null;
try {
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
address = sb.toString();
} catch (SocketException ex) {
ex.printStackTrace();
}
return address;
}
}
I would like to create a singleton that contains the MAC address of the system it is running on, based on a supplied network interface.
I have written the following code:
public class NodeMac {
private static final String INSTANCE = getMacAddress();
private static String networkInterfaceName;
#Value("${machine.network.interface}")
public void setNetworkInterfaceName(String networkInterfaceName) {
NodeMac.networkInterfaceName = networkInterfaceName;
}
private NodeMac() { }
public static String getInstance() {
return INSTANCE;
}
private static String getMacAddress() {
try {
NetworkInterface network = NetworkInterface.getByName(networkInterfaceName);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (SocketException | NullPointerException e) {
throw new RuntimeException(
"Failed to extract MAC address for network interface with name " + networkInterfaceName, e);
}
}
}
And in application.properties:
machine.network.interface=eno1
However, I can't find any way to get the property value that contains the name of the network interface. It is always null, no matter how I try to access it.
What is the correct way to do this? Is it an anti-pattern to have a property in a singleton?
Edit
So you're struggling to create single instance pojo class with injected #Value. If you can work with bean then this is the way to go:
#Component // This will default give you a single ton bean
public class NodeMac {
#Value("${machine.network.interface}")
private String networkInterfaceName;
public String getMacAddress() {
try {
NetworkInterface network = NetworkInterface.getByName(networkInterfaceName);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
return sb.toString();
} catch (SocketException | NullPointerException e) {
throw new RuntimeException(
"Failed to extract MAC address for network interface with name " + networkInterfaceName, e);
}
}
}
OLD
How do you come up with this expression:
String key = System.getProperty("machine.network.interface");
The machine unlikely have only one network interface so there can't be a single key returned.
Indeed, oracle already writes a tutorial here
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
This question already has answers here:
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
(2 answers)
Closed 5 years ago.
I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
#Override
public void onStart()
{
super.onStart();
onResume();
}
#Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
I propose two alternatives:
If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.
Is there a way in Java to tell it to return IPv6 only? I've tried everything and can't get it to work.
try
{
InetAddress inet = InetAddress.getByName(hostName);
boolean status = inet.isReachable(5000);
if (status)
{
System.out.println(inet.getCanonicalHostName() + " Host Reached\t" + java.net.Inet6Address.getByName(hostName).getHostAddress());
}
else
{
System.out.println(inet.getCanonicalHostName() + " Host Unreachable");
}
}
catch (UnknownHostException e)
{
System.err.println("Host does not exists");
}
catch (IOException e)
{
System.err.println("Error in reaching the Host");
}
The line I use to try to return IPv6 only:
System.out.println(inet.getCanonicalHostName() + " Host Reached\t" + java.net.Inet6Address.getByName(hostName).getHostAddress());
This keeps returning IPv4. Anyone have any idea of why its doing this?
java.net.Inet6Address does not override getByName()
so it will always return the specific IPv4-Address,
unless your parameter itself is in the form of an valid IPv6-Address, in this case this method will return an Inet6Address-Object.
For example:
getByName("stackoverflow.com") --> Inet4Address
getByName("2001:0db8:85a3:08d3:1319:8a2e:0370:7344") --> Inet6Address
InetAddress.getByName()-Documentation
Determines the IP address of a host, given the host's name. The host name can either be a machine name, such as "java.sun.com", or a
textual representation of its IP address. If a literal IP address is
supplied, only the validity of the address format is checked.
> For host specified in literal IPv6 address, either the form defined in
RFC 2732 or the literal IPv6 address format defined in RFC 2373 is
accepted.<
So if you want to get an IPv6-Address you need to define it within your parameter, or configure a DNS-Server to return the IPv6-Address instead of the IPv4-Address.
Another way to retrieve the IPv6-Address is using InetAddress.getAllByName("www.google.at") which returns all known IP-Addresses of the host.
For example you can use this method to filter the returned array, which return the first IPv6-Address or null if the host don't have one:
public Inet6Address getIPv6Addresses(InetAddress[] addresses) {
for (InetAddress addr : addresses) {
if (addr instanceof Inet6Address) {
return (Inet6Address) addr;
}
}
return null;
}
UPDATE:
For more functions, especially those affecting DNS-Servers, I recommend using the external library DNSJava, because the plain Java implementation of DNS support is poor.
http://www.dnsjava.org/
Current Code:
public class Ping
{
public void pingHost (String hostName)
{
try
{
InetAddress[] inet = InetAddress.getAllByName(hostName);
String address = this.getIPv4Addresses(inet).getHostAddress();
boolean status = this.getIPv6Addresses(inet).isReachable(5000);
if (status)
{
System.out.println(reverseDns(address) + " Host Reached\t" + this.getIPv6Addresses(inet).getHostAddress());
}
else
{
System.out.println(this.getIPv6Addresses(inet).getCanonicalHostName() + " Host Unreachable");
}
}
catch (UnknownHostException e)
{
System.err.println("Host does not exists");
}
catch (IOException e)
{
System.err.println("Error in reaching the Host");
}
}
public Inet6Address getIPv6Addresses(InetAddress[] addresses)
{
for (InetAddress addr : addresses)
{
if (addr instanceof Inet6Address)
{
return (Inet6Address) addr;
}
}
return null;
}
public Inet4Address getIPv4Addresses(InetAddress[] addresses)
{
for (InetAddress addr : addresses)
{
if (addr instanceof Inet4Address)
{
return (Inet4Address) addr;
}
}
return null;
}
public static String reverseDns(String hostIp) throws IOException
{
Resolver res = new ExtendedResolver();
Name name = ReverseMap.fromAddress(hostIp);
int type = Type.PTR;
int dclass = DClass.IN;
Record rec = Record.newRecord(name, type, dclass);
Message query = Message.newQuery(rec);
Message response = res.send(query);
Record[] answers = response.getSectionArray(Section.ANSWER);
if (answers.length == 0)
return hostIp;
else
return answers[0].rdataToString();
}
}
You could try to define JVM_ARGS
-Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true
with that props it will prefer IPv6 addr on InetAddress#getByName
More info: https://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/
I am developing a Java webservice application (with JAX-WS) that has to use two different proxies to establish separated connections to internet and an intranet. As solution I tried to write my own java.net.ProxySelector that returns a java.net.Proxy instance (of type HTTP) for internet or intranet.
In a little test application I try to download webpage via URL.openConnection(), and before I replaced the default ProxySelector with my own. But it results in an exception:
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:370)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:844)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:792)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:703)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1026)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at norman.test.ProxyTest.conntectToRmViaProxy(ProxyTest.java:42)
at norman.test.ProxyTest.main(ProxyTest.java:65)
Question: "Why tries the application to establish a connection via SOCKS, if my ProxySelector only returns a HTTP Proxy?"
2 Question: "Is there a alternative, to define different proxies for each connection?"
This is my ProxySelector:
public class OwnProxySelector extends ProxySelector {
private Proxy intranetProxy;
private Proxy extranetProxy;
private Proxy directConnection = Proxy.NO_PROXY;
private URI intranetAddress;
private URI extranetAddress;
/* (non-Javadoc)
* #see java.net.ProxySelector#connectFailed(java.net.URI, java.net.SocketAddress, java.io.IOException)
*/
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Nothing to do
}
/* (non-Javadoc)
* #see java.net.ProxySelector#select(java.net.URI)
*/
public List select(URI uri) {
ArrayList<Proxy> result = new ArrayList<Proxy>();
if(intranetAddress.getHost().equals(uri.getHost()) && intranetAddress.getPort()==uri.getPort()){
result.add(intranetProxy);
System.out.println("Adding intranet Proxy!");
}
else if(extranetAddress.getHost().equals(uri.getHost()) && extranetAddress.getPort()==uri.getPort()){
result.add(extranetProxy);
System.out.println("Adding extranet Proxy!");
}
else{
result.add(directConnection);
System.out.println("Adding direct connection!");
}
return result;
}
public void setIntranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
intranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
intranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void setExtranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
extranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
extranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void clearIntranetProxy(){
intranetProxy = Proxy.NO_PROXY;
}
public void clearExtranetProxy(){
extranetProxy = Proxy.NO_PROXY;
}
public void setIntranetAddress(String address) throws URISyntaxException{
intranetAddress = new URI(address);
}
public void setExtranetAddress(String address) throws URISyntaxException{
extranetAddress = new URI(address);
}
}
This is the test class:
public class ProxyTest {
OwnProxySelector ownSelector = new OwnProxySelector();
public ProxyTest(){
ownSelector.setIntranetProxy("intranet.proxy", 8123);
try {
ownSelector.setIntranetAddress("http://intranet:80");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ownSelector.setExtranetProxy("", 0);
try {
ownSelector.setExtranetAddress("http://www.example.com:80");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ProxySelector.setDefault(ownSelector);
}
public void conntectToRmViaProxy(boolean internal, String connectAddress){
try {
URL url = new URL(connectAddress);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println(conn.getResponseMessage());
}
else{
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int tmp = reader.read();
while(tmp != -1){
System.out.print((char)tmp);
tmp = reader.read();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
ProxyTest proxyText = new ProxyTest();
proxyText.conntectToRmViaProxy(true, "http://intranet:80");
}
}
Ok, I have found the problem.
The HttpURLConnection did the OwnProxySelector.select() twice if the requested URL does not contain a port.
At first, HttpURLConnection invoked the select() with an URI, with the Scheme of "http" but no port. The select() checks whether the host address and port are euqal to intranetAddress or extranetAddress. This didn't match, because the port was not given. So the select return a Proxy for a direct connection.
At the second HttpURLConnection invoked the select() with an URI, with the Scheme of "socket" and port 80. So, because the select() checks host address and port, but not the scheme, it returned a HTTP proxy.
Now here is my corrected version of OwnProxySelector. It checks the scheme and sets the default port for HTTP or HTTPS if the port is not given by the URI. Also it asks the Java standard ProxySelector, if no HTTP or HTTPS scheme is given.
public class OwnProxySelector extends ProxySelector {
private ProxySelector defaultProxySelector;
private Proxy intranetProxy;
private Proxy extranetProxy;
private Proxy directConnection = Proxy.NO_PROXY;
private URI intranetAddress;
private URI extranetAddress;
public OwnProxySelector(ProxySelector defaultProxySelector){
this.defaultProxySelector = defaultProxySelector;
}
/* (non-Javadoc)
* #see java.net.ProxySelector#connectFailed(java.net.URI, java.net.SocketAddress, java.io.IOException)
*/
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Nothing to do
}
/* (non-Javadoc)
* #see java.net.ProxySelector#select(java.net.URI)
*/
public List select(URI uri) {
ArrayList<Proxy> result = new ArrayList<Proxy>();
if(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")){
int uriPort = uri.getPort();
// set default http and https ports if port is not given in URI
if(uriPort<1){
if(uri.getScheme().equalsIgnoreCase("http")){
uriPort = 80;
}
else if(uri.getScheme().equalsIgnoreCase("https")){
uriPort = 443;
}
}
if(intranetAddress.getHost().equals(uri.getHost()) && intranetAddress.getPort()==uriPort){
result.add(intranetProxy);
System.out.println("Adding intranet Proxy!");
}
else if(extranetAddress.getHost().equals(uri.getHost()) && extranetAddress.getPort()==uriPort){
result.add(extranetProxy);
System.out.println("Adding extranet Proxy!");
}
}
if(result.isEmpty()){
List<Proxy> defaultResult = defaultProxySelector.select(uri);
if(defaultResult!=null && !defaultResult.isEmpty()){
result.addAll(defaultResult);
System.out.println("Adding Proxis from default selector.");
}
else{
result.add(directConnection);
System.out.println("Adding direct connection, because requested URI does not match any Proxy");
}
}
return result;
}
public void setIntranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
intranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
intranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void setExtranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
extranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
extranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void clearIntranetProxy(){
intranetProxy = Proxy.NO_PROXY;
}
public void clearExtranetProxy(){
extranetProxy = Proxy.NO_PROXY;
}
public void setIntranetAddress(String address) throws URISyntaxException{
intranetAddress = new URI(address);
}
public void setExtranetAddress(String address) throws URISyntaxException{
extranetAddress = new URI(address);
}
}
But it is curious to me, that the HttpURLConnection did a second invoke of select(), when it got a direct connection Proxy from the first invoke.