Android get Tcp connection log - android

I have some trouble in getting Tcp connection log of all apps. Basically, I just read the log file "/proc/Pid/net/tcp" as used here:
http://code.google.com/p/iptableslog/source/browse/src/com/googlecode/networklog/NetStat.java?r=60cb640ac27f8b4fb06f11d9d81c94591a531862
But all the destination ip address are 0.0.0.0, though some apps are connecting to Internet.
Here is my source code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textmpid = (TextView) findViewById(R.id.textView2);
Button buttonLoadTrafficStats = (Button) findViewById(R.id.button1);
buttonLoadTrafficStats.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ActivityManager mActivityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses();
int i = 1;
int a;
String b;
int c;
for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess){
//Get name, Pid, Uid of all running process
System.out.println("Application: " +i+ " PID: " + amProcess.pid+ " (processName= " + amProcess.processName + " UID= "+amProcess.uid+")");
Log.i("Application", (i++) + "PID: " + amProcess.pid + "(processName=" + amProcess.processName + "UID="+amProcess.uid+")");
i++;
textmpid.setText("PID: "+ String.valueOf(amProcess.pid));
a = amProcess.pid;
b = String.valueOf(amProcess.pid);
ArrayList<Connection> connections = new ArrayList<Connection>();
try {
BufferedReader in = new BufferedReader(new FileReader("/proc/" + a + "/net/tcp"));
String line = b;
int z;
while((line = in.readLine()) != null) {
System.out.println(" tcp Netstat line: " + line);
line = line.trim();
String[] fields = line.split("\\s+", 10);
int fieldn = 0;
for(String field : fields) {
System.out.println(" tcp Field " + (fieldn++) + ": [" + field + "]");
int m = fieldn;
String n = field;
}
if(fields[0].equals("sl")) {
continue;
}
Connection connection = new Connection();
String src[] = fields[1].split(":", 2);
String dst[] = fields[2].split(":", 2);
System.out.println(" tcp Netstat: fields[1] " + fields[1]+" fields[2] " + fields[2]);
System.out.println(" tcp Netstat: src[0] " + src[0] +" src[1] " + src[1]);
connection.src = getAddress(src[0]);
System.out.println(" tcp Netstat: connection.src " + connection.src);
connection.spt = String.valueOf(getInt16(src[1]));
System.out.println(" tcp Netstat: connection.spt " + connection.spt);
connection.dst = getAddress(dst[0]);
System.out.println(" tcp Netstat: connection.dst " + connection.dst);
connection.dpt = String.valueOf(getInt16(dst[1]));
System.out.println(" tcp Netstat: connection.dpt " + connection.dpt);
connection.uid = fields[7];
System.out.println(" tcp Netstat: connection.uid " + connection.uid);
connections.add(connection);
}
}
catch(Exception e) {
System.out.println(" checknetlog() Exception: " + e.toString());
}
}
}
});
}
public class Connection {
String src;
String spt;
String dst;
String dpt;
String uid;
}
final String states[] = { "ESTBLSH", "SYNSENT", "SYNRECV", "FWAIT1", "FWAIT2", "TMEWAIT",
"CLOSED", "CLSWAIT", "LASTACK", "LISTEN", "CLOSING", "UNKNOWN"
};
private final String getAddress(final String hexa) {
try {
final long v = Long.parseLong(hexa, 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final String getAddress6(final String hexa) {
try {
final String ip4[] = hexa.split("0000000000000000FFFF0000");
if(ip4.length == 2) {
final long v = Long.parseLong(ip4[1], 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} else {
return "-2.-2.-2.-2";
}
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final int getInt16(final String hexa) {
try {
return Integer.parseInt(hexa, 16);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return -1;
}
}
}
And I also added the permission "uses-permission android:name="android.permission.INTERNET".
Could someone kindly point out where I did wrong?

Oh, when I check this log "/proc/Pid/net/tcp6", I found the correct destination ip address. It seems that the connection type is tcp6 instead of tcp.

Related

Selendroid webdriver initialisation error occuring

I am making an android application which will login to my college website then clicks on attendance button on the page , scraps data ,perform some calculations and shows to the user but I can't find any way from here. I am using selendroid for this. The problem is with the driver variable. In java application I can use ChromeDriver but for android what to use?
package com.example.jtx.gneattendance;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.List;
import io.selendroid.SelendroidCapabilities;
import io.selendroid.SelendroidDriver;
import io.selendroid.standalone.SelendroidLauncher;
public class MainActivity extends AppCompatActivity {
int count = 0;
String arr[] = new String[15];
String atten = "";
TextView text;
public void cnt() throws Exception
{
WebDriver driver =null;
driver.get("https://academics.gndec.ac.in");
driver.findElement(By.id("username")).sendKeys("xxxxxxxxx");
driver.findElement(By.id("password")).sendKeys("xxxxxxxxx");
driver.findElement(By.name("submit")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div/div[2]/form/button")).click();
List<WebElement> rows = driver.findElements(By.xpath("/html/body/form/table/tbody/tr"));
String p[] = new String[rows.size() + 1];
int pheld[] = new int[rows.size() + 1];
int pattende[] = new int[rows.size() + 1];
Double ppercent[] = new Double[rows.size() + 1];
for (int i = 1; i <= rows.size(); i++) {
p[i] = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[2]")).getText();
pheld[i] = Integer.parseInt(driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[4]")).getText());
pattende[i] = Integer.parseInt(driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[5]")).getText());
ppercent[i] = Double.valueOf((driver.findElement(By.xpath("/html/body/form/table/tbody/tr[" + i + "]/td[6]")).getText()));
if (ppercent[i] < 75.0) {
lecreq(pattende[i], pheld[i]);
}
arr[i] = " Subject name=" + p[i] + "<br> Lectures held=" + pheld[i] + " <br> Lectures Attended=" + pattende[i] + " <br> Percentage=" + ppercent[i] + " <br> Lectures needed=" + count + "<br><br><br>";
// System.out.println(arr[i]);
text = findViewById(R.id.textView1);
text.setText(arr[i]);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
cnt();
} catch (Exception e) {
e.printStackTrace();
}
}
public void lecreq(int m, int n) {
if ((m * 100 / n) < 75.0) {
m++;
n++;
count++;
lecreq(m, n);
}
}
}

Android App Communicating with USB CDC Device

I am Developing Android App That Receive Data From USB CDC Device.
Thinking that my android phone is host. The Device should get power from the android phone only. The cable Used for Data Transfer and power is Same.
But here Data Not Receiving from USB CDC Device to Mobile.
Here is code snippet from what I have tried
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Iterator;
public class MainActivity extends Activity {
boolean Run= true;
boolean Communication_Ok;
Button btn;
UsbManager manager;
UsbDevice device;
UsbDeviceConnection connection;
UsbInterface Inf;
UsbEndpoint Data_In_End_Point =null;
UsbEndpoint Data_Out_End_Point =null;
ByteBuffer buffer = ByteBuffer.allocate(255);
UsbRequest request = new UsbRequest();
static int s1,s2,s3;
TextView tv1;
PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.btn);
tv1=(TextView)findViewById(R.id.tv1);
check_devices();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
call_next_Intent();
if (!Receive.isAlive())
Receive.start();
}
});
}
private void call_next_Intent() {
Intent Home=new Intent(MainActivity.this,Home.class);
startActivity(Home);
}
private void check_devices()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
HashMap<String , UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String returnValue = "";
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
manager.requestPermission(device, mPermissionIntent);
returnValue += "Name: " + device.getDeviceName();
returnValue += "\nID: " + device.getDeviceId();
returnValue += "\nProtocol: " + device.getDeviceProtocol();
returnValue += "\nClass: " + device.getDeviceClass();
returnValue += "\nSubclass: " + device.getDeviceSubclass();
returnValue += "\nProduct ID: " + device.getProductId();
returnValue += "\nVendor ID: " + device.getVendorId();
returnValue += "\nInterface count: " + device.getInterfaceCount();
for (int i = 0; i < device.getInterfaceCount(); i++) {
Inf = device.getInterface(i);
returnValue += "\n Interface " + i;
returnValue += "\n\tInterface ID: " + Inf.getId();
returnValue += "\n\tClass: " + Inf.getInterfaceClass();
returnValue += "\n\tProtocol: " + Inf.getInterfaceProtocol();
returnValue += "\n\tSubclass: " + Inf.getInterfaceSubclass();
returnValue += "\n\tEndpoint count: " + Inf.getEndpointCount();
for (int j = 0; j < Inf.getEndpointCount(); j++) {
returnValue += "\n\t Endpoint " + j;
returnValue += "\n\t\tAddress: " + Inf.getEndpoint(j).getAddress();
returnValue += "\n\t\tAttributes: " + Inf.getEndpoint(j).getAttributes();
returnValue += "\n\t\tDirection: " + Inf.getEndpoint(j).getDirection();
returnValue += "\n\t\tNumber: " + Inf.getEndpoint(j).getEndpointNumber();
returnValue += "\n\t\tInterval: " + Inf.getEndpoint(j).getInterval();
returnValue += "\n\t\tType: " + Inf.getEndpoint(j).getType();
returnValue += "\n\t\tMax packet size: " + Inf.getEndpoint(j).getMaxPacketSize();
}
}
}
tv1.setText(returnValue);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if(device != null)
{
connection = manager.openDevice(device);
if (!connection.claimInterface(device.getInterface(0), true))
{
return;
}
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
connection.controlTransfer(0x21, 0x22, 0x1, 0, null, 0, 0);//DTR signal
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
connection.controlTransfer(0x40, 0x03,0x001A, 0, null, 0, 0);//For baudrate
Inf = device.getInterface(0);
for (int i = 0; i < device.getInterfaceCount(); i++) {
// communications device class (CDC) type device
if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
Inf = device.getInterface(i);
// find the endpoints
for (int j = 0; j < Inf.getEndpointCount(); j++) {
if (Inf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT && Inf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
// from android to device
Data_Out_End_Point = Inf.getEndpoint(j);
}
if (Inf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN && Inf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
// from device to android
Data_In_End_Point = Inf.getEndpoint(j);
}
}
}
}
}
}
else
{
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
public Thread Receive = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] Recieved_Data;
int i;
buffer.clear();
while (Run){
request.initialize(connection, Data_In_End_Point);
request.queue(buffer,255);
if (connection.requestWait() !=null)
{
Recieved_Data=buffer.array();
if (Recieved_Data[0]==0x02 && Recieved_Data[2]==0x03){
if (Recieved_Data[1]==0x11){
s1++;
}
else if (Recieved_Data[1]==0x22){
s2++;
}
else if (Recieved_Data[1]==0x33){
s3++;
}
}
}
}
}
});
}

(Android) How to find IP addresses of other devices connected to my Wi-fi?

I found a solution. But it takes a long time. Given code tries to ping every IP addresses under the subnet. For example if 100ms is given as timeout then 25.5 Second is needed to complete whole process. What's the optimal way to do it?
public class MainActivity extends Activity {
Button button;
EditText textview;
public String s_dns1 ;
public String s_dns2;
public String s_gateway;
public String s_ipAddress;
public String s_leaseDuration;
public String s_netmask;
public String s_serverAddress;
TextView info;
DhcpInfo d;
WifiManager wifii;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (EditText)findViewById(R.id.ipList);
}
public void NetworkDetect(View v)
{
wifii = (WifiManager) getSystemService(Context.WIFI_SERVICE);
d = wifii.getDhcpInfo();
s_dns1 = "DNS 1: " + String.valueOf(d.dns1);
s_dns2 = "DNS 2: " + String.valueOf(d.dns2);
s_gateway = "Default Gateway: " + String.valueOf(d.gateway);
s_ipAddress = "IP Address: " + String.valueOf(d.ipAddress);
s_leaseDuration = "Lease Time: " + String.valueOf(d.leaseDuration);
s_netmask = "Subnet Mask: " + String.valueOf(d.netmask);
s_serverAddress = "Server IP: " + String.valueOf(d.serverAddress);
String connections = "";
InetAddress host;
StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try
{
host = InetAddress.getByName(intToIp(d.dns1));
byte[] ip = host.getAddress();
System.out.println("Start: ");
for(int i = 1; i <= 254; i++)
{
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if(address.isReachable(100))
{
System.out.println(address + " machine is turned on and can be pinged");
connections+= address+"\n";
textview.append(address.toString()+"\n");
}
else if(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " machine is known in a DNS lookup");
}
}
System.out.println("End");
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println(connections);
}
public String intToIp(int addr) {
return ((addr & 0xFF) + "." +
((addr >>>= 8) & 0xFF) + "." +
((addr >>>= 8) & 0xFF) + "." +
((addr >>>= 8) & 0xFF));
}
}

How to get all IP address of systems connected to same Wi-Fi network in android

Can someone tell me how to find the IP addrss of all the systems connected to same network in Android programatically. DHCPInfo class gives only the ipaddress assigned to our android device but not for the other devices connected to the same network. How to get ipaddress of other devices connected to same network?
First get the host ip by this
public String s_dns1 ;
public String s_dns2;
public String s_gateway;
public String s_ipAddress;
public String s_leaseDuration;
public String s_netmask;
public String s_serverAddress;
TextView info;
DhcpInfo d;
WifiManager wifii;
wifii = (WifiManager) getSystemService(Context.WIFI_SERVICE);
d = wifii.getDhcpInfo();
s_dns1 = "DNS 1: " + String.valueOf(d.dns1);
s_dns2 = "DNS 2: " + String.valueOf(d.dns2);
s_gateway = "Default Gateway: " + String.valueOf(d.gateway);
s_ipAddress = "IP Address: " + String.valueOf(d.ipAddress);
s_leaseDuration = "Lease Time: " + String.valueOf(d.leaseDuration);
s_netmask = "Subnet Mask: " + String.valueOf(d.netmask);
s_serverAddress = "Server IP: " + String.valueOf(d.serverAddress);
d.dns1 is host ip
Now get connected ips by this
String connections = "";
InetAddress host;
try
{
host = InetAddress.getByName(intToIp(d.dns1));
byte[] ip = host.getAddress();
for(int i = 1; i <= 254; i++)
{
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if(address.isReachable(100))
{
System.out.println(address + " machine is turned on and can be pinged");
connections+= address+"\n";
}
else if(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " machine is known in a DNS lookup");
}
}
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println(connections);
intToIp
public String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
((i >> 24) & 0xFF);
}
private class Task extends AsyncTask<void void="">{
InetAddress[] inetAddress = null;
List<string> hostList = new ArrayList<string>();
#Override
protected Void doInBackground(Void... arg0) {
doTest();
}
#Override
protected void onPostExecute(Void result) {
ArrayAdapter<string> adapter
= new ArrayAdapter<string>(
AndroidInetActivity.this,
android.R.layout.simple_list_item_1,
hostList);
resultList.setAdapter(adapter);
}
private void doTest(){
String host = hostinput.getText().toString();
inetAddress = InetAddress.getAllByName(host);
for(int i = 0; i < inetAddress.length; i++){
hostList.add(inetAddress[i].getClass() + " -\n"
+ inetAddress[i].getHostName() + "\n"
+ inetAddress[i].getHostAddress());
}
}
}
}

My Android application is crashing if it is not connected to wifi

package com.example.intracollegeapp;// package name
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import LibPack.UserInfoLib;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class LoginForm extends Activity {
Button login;
TextView username;
TextView password;
UserInfoLib ui;
long msgLength;
long bitLength;
char msg[];
long requiredBits;
long requiredBytes;
int toPad[];
private static final String NAMESPACE = "link to server package on which webservices are stored";
private static final String URL = "link to wsdl file stored on server";
private static final String SOAP_ACTION = "IntraCollegeWS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
login=(Button)findViewById(R.id.butLogin);
username=(TextView)findViewById(R.id.editText1);
password=(TextView)findViewById(R.id.editText2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ui= new UserInfoLib();
ui.userId=username.getText().toString();
ui.password=getSHA1(password.getText().toString());
ui=(UserInfoLib)callService(objectToString(ui), "UserLogin", "userInfo");
//ui=(UserInfoLib)stringToObject(temp);
if(ui.firstName.equals("")){
Toast.makeText(v.getContext(), "Please Verify User Name Or Password", Toast.LENGTH_LONG).show();
finish();
}else{
Toast.makeText(v.getContext(), "Login Successfull", Toast.LENGTH_LONG).show();
System.out.println("NAME :"+ui.firstName);
Intent i = new Intent(v.getContext(), MainForm.class);
i.putExtra("uid", ui);
startActivity(i);
finish();
}
}
});
}
public long leftRotateBy(long l, int times) {
return ((l << times) & 0xFFFFFFFFl) | ((l & 0xFFFFFFFFl) >> (32 - times));
}
public int getByteAt(int at) {
if (at < msgLength) {
return (msg[at]);
} else {
at = at - (int) msgLength;
return toPad[at];
}
}
public void padBits(String pass) {
System.out.println("\n\n\n\n");
msg = pass.toCharArray();
msgLength = msg.length;
bitLength = msgLength * 8;
System.out.println("Msg Bit Length: " + bitLength);
System.out.println("MSg Byte Length: " + msgLength);
System.out.println("Required Minimum Bits: " + (bitLength + 65));
long remainder = (bitLength + 65) % 512;
System.out.println("Mod (Bits): " + remainder);
if (remainder == 0) {
requiredBits = 65;
System.out.println("No Padding Needed.");
} else {
requiredBits = (512 - remainder) + 65;
System.out.println(requiredBits + " Bits Padding Needed.");
}
requiredBytes = requiredBits / 8;
toPad = new int[(int) requiredBytes];
System.out.println("Required Bits: " + requiredBits);
System.out.println("Required Bytes: " + requiredBytes);
// manually append 1 to start of pad bits...
toPad[0] = 0x80;
for (int i = 1; i < requiredBytes - 8; i++) {
toPad[i] = 0;
}
long temp = bitLength;
for (int i = (int) (requiredBytes - 1); i >= (int) (requiredBytes - 8); i--) {
int t = (int) (temp & 0xff);
temp = temp >> 8;
toPad[i] = t;
}
System.out.println("TO PAD: ");
for (int i = 0; i < requiredBytes; i++) {
System.out.print(Integer.toHexString(toPad[i]) + " ");
}
System.out.println();
}
public String getSHA1(String pass) {
int kconst[] = new int[]{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6};
long h0 = 0x67452301;
long h1 = 0xEFCDAB89;
long h2 = 0x98BADCFE;
long h3 = 0x10325476;
long h4 = 0xC3D2E1F0;
long a, b, c, d, e;
padBits(pass);
long totalLength = msgLength + requiredBytes;
System.out.println("TOTAL LENGTH: " + totalLength);
System.out.println("BLOCKS: " + (totalLength / 8));
long w[] = new long[80];
for (int i = 0; i < (int) totalLength; i += 64) {
for (int j = i, kk = 0; j < (i + 64); j += 4, kk++) {
w[kk] = 0xffffffffl & ((getByteAt(j) << 24) | (getByteAt(j + 1) << 16) | (getByteAt(j + 2) << 8) | (getByteAt(j + 3)));
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
for (int kk = 16; kk < 80; kk++) {
w[kk] = (w[kk - 3] ^ w[kk - 8] ^ w[kk - 14] ^ w[kk - 16]);
w[kk] = leftRotateBy(w[kk], 1);
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
long temp = 0;
for (int t = 0; t < 20; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | ((~b) & d)) + e + w[t] + kconst[0];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 20; t < 40; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[1];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 40; t < 60; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | (b & d) | (c & d)) + e + w[t] + kconst[2];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 60; t < 80; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[3];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFFl;
h1 = (h1 + b) & 0xFFFFFFFFl;
h2 = (h2 + c) & 0xFFFFFFFFl;
h3 = (h3 + d) & 0xFFFFFFFFl;
h4 = (h4 + e) & 0xFFFFFFFFl;
}
return Long.toHexString(h0) + Long.toHexString(h1) + Long.toHexString(h2) + Long.toHexString(h3) + Long.toHexString(h4);
}
Object callService(String INPUT_DATA, String METHOD_NAME, String PARAMETER_NAME){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo pi = new PropertyInfo();
pi.setName(PARAMETER_NAME);
pi.setValue(INPUT_DATA);
pi.setType(String.class);
request.addProperty(pi);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject)envelope.bodyIn;
String resp = resultsRequestSOAP.getPrimitivePropertyAsString("return");
return stringToObject(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Object stringToObject(String inp){
byte b[] = Base64.decode(inp);
Object ret = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
ret = (Object) in.readObject();
bis.close();
in.close();
} catch(Exception e) {
System.out.println("NOT DE-SERIALIZABLE: " + e);
}
return ret;
}
String objectToString(Object obj){
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
b = bos.toByteArray();
} catch(Exception e) {
System.out.println("NOT SERIALIZABLE: " + e);
}
return Base64.encode(b);
}
}
/* i have developed an android application which connects to server for login purpose. For connection i have used ksoap2 library. Intracollege webservice is stored on server. The application works fine when connected to server using wifi. if it is not connected to wifi it displays message "application is crashed" and then application stops working.
I only want to display a simple message "Application is not connected to server" if it is not connected to server using wifi.*/
Try this........
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
When status is true do your login process.Otherwise show message "Application is not connected to server".
To check for the internet connection try this out
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Check this code, this will help you :
Initialize in the class where you want to check network availability.
OtherUtils otherUtils = new OtherUtils();
if (!otherUtils.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "No Network Available", Toast.LENGTH_LONG).show();
return;
}
Add below class:
public class OtherUtils{
Context context;
public boolean isNetworkAvailable(Context context) {
this.context = context;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
// boitealerte(this.getString(R.string.alertNoNetwork),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
This will surely help you.

Categories

Resources