[Q] Android get the actual ip address - Java for Android App Development

Hi, I've this method that looks for the IP of my device:
Code:
public String getLocalIpAddress(boolean useIPv4){
String ritorno="";
try{ List<NetworkInterface>interfaces=Collection.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().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
ritorno=sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port suffix
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return ritorno;
Now, the issue is that when I do intf.getInetAddresses(), I get a collection of the addresses bound to intf, but I need the address relative to the last connection. How can I solve my issue?

Related

how to know http data

hi,
I'am developing a webbrowser control using the dll html view in c#!
I want add a progressbar to my program witch represent the progress of open pages!
I have the implementation of the class WebBrowserProgressChangedEventArgs:
public class WebBrowserProgressChangedEventArgs : EventArgs
{
private long current_progress;
private long maximum_progress;
#region Construtor
public WebBrowserProgressChangedEventArgs(long currentProgress, long maximumProgress)
: base()
{
this.current_progress = currentProgress;
this.maximum_progress = maximumProgress;
}
#endregion
#region Propriedades
public long CurrentProgress
{
get { return this.current_progress; }
}
public long MaximumProgress
{
get { return this.maximum_progress; }
}
#endregion
}
I create the event, and I dont know how to fire the event because when fire i most to pass the current_progress and the maximum_progress, of the open page to the WebBrowserProgressChangedEventArgs, and i dont know how to obtain that.
The code when I call the event is below:
Note: The position when i call the event is not the correct, but first i want to know how to obtain the values for the event.
OnProgressChanged(new WebBrowserProgressChangedEventArgs(current_progress???, maximum_progress???));
switch (myhtml.code)
{
case (int)NM.INLINE_IMAGE:
case (int)NM.HOTSPOT:
case (int)NM.BEFORENAVIGATE:
OnNavigating(new WebBrowserNavigatingEventArgs(target));
break;
case (int)NM.NAVIGATECOMPLETE:
OnNavigated(new WebBrowserNavigatedEventArgs(target));
break;
case (int)NM.DOCUMENTCOMPLETE:
OnDocumentCompleted(new WebBrowserDocumentCompletedEventArgs(target));
break;
case (int)NM.TITLECHANGE:
case (int)NM.TITLE:
m_tit= target;
OnDocumentTitleChanged(new EventArgs());
break;
}
And the function is described here
Code Snippet
protected virtual void OnProgressChanged(WebBrowserProgressChangedEventArgs e)
{
MessageBox.Show("Progresso" + e.CurrentProgress);
if(ProgressChanged!=null)
{
ProgressChanged(this,e);
}
}
Anyone can help me to do that?
Any exemple by this?
Thanks,
Rui Eusébio

NullReferenceExpection in 2nd HttpWebResponse

HTML:
Anybody Pls help me with this I am making a http post request to a server ,
on doing the 1st request i'm able to get the response & i'm able to get the
session id that is been used for further polling & used i the second request as
the cookie value.But on making the second request i'm getting the NullReference
Expection in the response , When i am monitoring it on a Packet capturing
software i find that i'm getting the required data in the captured packets but
unable to read it in the response of the second request in the application code
& i'm getting a NullReferenceExpection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;
using System.Windows.Threading;
namespace MunduNetworkingHttp
{
public partial class MainPage : PhoneApplicationPage
{
private HttpWebRequest UniversalRequest;
private HttpWebRequest request;
private HttpWebResponse response;
private Stream stream;
// Constructor
public MainPage()
{
InitializeComponent();
}
public static string res1;
public static string res2;
public static string sessionid;
public static string valueOfSession;
//Here the Server Link is Specified.
string Server = "server link here";
private void button1_Click(object sender, RoutedEventArgs e)
{
//Here we are callinh the method of the first request.
first_Request();
}
public void first_Request()
{
if (null == UniversalRequest)
{
UniversalRequest = (HttpWebRequest)WebRequest.Create(Server);
UniversalRequest.CookieContainer = new CookieContainer();
UniversalRequest.CookieContainer.Add(new Uri(Server),new Cookie("SESSION","0"));
UniversalRequest.Accept = "*/*";
UniversalRequest.Method = "POST";
}
UniversalRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback1), UniversalRequest);
}
private void GetRequestStreamCallback1(IAsyncResult asynchronousReault1)
{
string XMl_REQUEST1 = "<SAMPLE><Xml string to be sent to server on 1st request'/></SAMPLE>";
request = (HttpWebRequest)asynchronousReault1.AsyncState;
stream= request.EndGetRequestStream(asynchronousReault1);
byte[] postBytes1 = Encoding.UTF8.GetBytes(XMl_REQUEST1);
stream.Write(postBytes1, 0, postBytes1.Length);
stream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback1), request);
}
private void GetResponseCallback1(IAsyncResult asynchronousResult1)
{
request = (HttpWebRequest)asynchronousResult1.AsyncState;
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult1);
stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string responseString1 = streamReader.ReadToEnd();
stream.Close();
streamReader.Close();
//Retreving the value of the session Id.
valueOfSession = (retrive the value from responseString1);
response.Close();
request.Abort();
second_Request();
}
public void second_Request()
{
UniversalRequest = (HttpWebRequest)WebRequest.Create(Server);
UniversalRequest.CookieContainer = new CookieContainer();
UniversalRequest.CookieContainer.Add(new Uri(Server), new Cookie("SESSTOOLBARMUNDU", valueOfSession));
UniversalRequest.ContentType = "application/xml";
UniversalRequest.Method = "POST";
UniversalRequest.Accept = "*/*";
UniversalRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback2), UniversalRequest);
}
private void GetRequestStreamCallback2(IAsyncResult asynchronousResult2)
{
string XMLREQUEST2 = "<SAMPLE2><Xml string data to be sent to the server on 2nd request to the server /></SAMPLE2>";
request = (HttpWebRequest)asynchronousResult2.AsyncState;
stream = request.EndGetRequestStream(asynchronousResult2);
byte[] postBytes2 = Encoding.UTF8.GetBytes(XMLREQUEST2);
stream.Write(postBytes2, 0, postBytes2.Length);
stream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback2), request);
}
private void GetResponseCallback2(IAsyncResult asynchronousResult2)
{
request = (HttpWebRequest)asynchronousResult2.AsyncState;
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult2);// here is where i get the NullReferenceExpection
stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string responseString2 = streamReader.ReadToEnd();
stream.Close();
streamReader.Close();
response.Close();
}
}
}

[Q]Service Socket closed by Background Foreground Lifecycle

I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.

Intercept traffic

Hello,
I was wondering if anyone knows how to intercept all the traffic generated by the phone by using the VpnService class
from Android ?
So far I managed to create a virtual tunnel interface by using VpnService. However this interface intercepts only the traffic that
is directed to it( e.g. ping or telnet on the IP address of the tunnel interface ) and afterwards it redirects that traffic towards a server
( in my case, I considered, for simplicity, the server to be the loopback interface ). The rest of the traffic is not intercepted by the tunnel
interface.
If anyone could give me a hint or a code snippet on how to intercept all the traffic, I'd appreciate it very much.
Thank you !
Code:
public class VPNService extends VpnService {
private Thread mThread;
private ParcelFileDescriptor mInterface;
private FileInputStream in;
private FileOutputStream out;
private DatagramChannel tunnel;
//private SocketChannel tunnel;
private String TAG = "VPNService";
//a. Configure a builder for the interface.
Builder builder = new Builder();
// Services interface
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("VPNService")
.addAddress("192.168.0.1", 24)
.addRoute("0.0.0.0", 0).establish();
//b. Packets to be sent are queued in this input stream.
in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
tunnel = DatagramChannel.open();
//tunnel = SocketChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.configureBlocking(false);
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
ByteBuffer packet = ByteBuffer.allocate(32767);
//e. Use a loop to pass packets.
while (true) {
int length = in.read(packet.array());
//Log.i(TAG,packet.array().toString());
if (length > 0){
packet.limit(length);
tunnel.write(packet);
packet.clear();
}
Thread.sleep(100);
}
} catch (Exception e) {
// Catch any exception
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
tunnel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, "MyVpnRunnable");
//start the service
mThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}
Did you take a look at ToyVpn example from SDK?
I believe it's possible to tune it up to work with OpenVPN server.

Starting chronometer with if condition comparing strings

I have an android application that is receiving a string from an arduino via Bluetooth, names the string "data" and displays it by setting a TextView to the string "data". I want a chronometer to start when the incoming string matches a predefined string.
For example:
Code:
if data.equals(startChrono)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
I actually have the arduino sending a "g" and am setting my string goL to be "g" but cannot get the chronometer to start when the g is received. My TextView shows the g. Code is below. I've tried several things and at a loss. Using same code for chronometer.start() with onClickListener with a button works great. I just need it to start the chronometer when i receive a specific string from the arduino.
Code:
beginListenForData();
// text.setText("Bluetooth Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; // This is the ASCII code for a newline
// character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
String goL = "g";
String goR = "f";
chronometerLeft = (Chronometer)findViewById(R.id.chronometerLeft);
chronometerRight = (Chronometer)findViewById(R.id.chronometerRight);
if(data.equals(goL)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
if(data.equals(goR))
chronometerRight.setBase(SystemClock.elapsedRealtime());
chronometerRight.start();
}
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
Sorry to bother, but in your while loop condition, what does the '!' before Thread do?

Categories

Resources