Getting a MAC address from the IP's retrieved from a ping sweep - ping

Basically I have 2 bits of code one will do a ping sweep of a network range and then one will retrieve a MAC address from a given IP.
What I would like to do is incorporate these two pieces of code so when the ping sweep is performed it shows the MAC address in the output next to the IP addresses.
The MAC address retrieval code is as follows...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test118;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test118 {
public static String command;
public String ip = "192.168.0.4";
Test118() {
command = "arp -a " + ip;
}
public void viewMac() {
String process = null;
String mac[] = new String[5];
String rmac[] = new String[10];
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
int i = 0;
while ((line = bufferedreader.readLine()) != null) {
mac[i] = line;
i++;
}
rmac = mac[3].split(" ");
System.out.println(rmac[2]);
} catch (Exception e) {
System.out.println("mac cant find");
}
}
public static void main(String[] args) throws Exception {
Test118 r = new Test118();
r.viewMac();
}
}
The ping sweep is as follows...
package pingstestnew;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 142; i <= 145; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " Host is reachable");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " Hostname Resolved, Host is reachable");
}
else
{
System.out.println(address + " Host Unreachable");
}
}
}
}

Related

migrating encrypted data to Sql server from MYSQL server

We have aes-256 encryption for some data in one of the tables and we are migrating this to sql server. The problem is that we cannot decrypt the data in sql server due to incompatibility. Is there any way we can encrypt data in MYSQL in a way which is compatible with sql server aswell. Any advise ?
if you know the secretkey then you can decrypt the data see following code for encryption and decryption of AES-256 . the code is written in JAVA
check this link AES-256 Password Based Encryption/Decryption in Java
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}

Database connection error in Selenium

I've written a class which fetcheS data from the databasE:
#Test
void ts() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root");
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery("select * from seleniumusers");
while(rs.next()){
name=rs.getString("firstname");
System.out.println(name);
e(mysql)
But on running the test from testng once the browser gets open it gives and error:
Warning: mysql_pconnect() [function.mysql-pconnect]: Can't connect to MySQL server on 'localhost' (10061) in C:\Program Files\vtigercrm-5.2.1\apache\htdocs\vtigerCRM\adodb\drivers\adodb-mysql.inc.php on line 373
public WebDriverWait wait;
String filename;
File file;
Workbook RegExcel = null;
Row row = null;
Sheet RegExcelSheet = null;
FileInputStream inputStream;
public String[][] excelDataValue;
public int rowCount;
public List<WebElement> AllRegularization=null;;
String projectPath = System.getProperty("user.dir");
#Given("^User Save Excel At Said Location$")
public void user_save_excel_at_said_location() throws Throwable {
filename="RegDates.xlsx";
file = new File (projectPath +"\\"+ filename);
}
#When("^Excel File Is Readable$")
public void excel_file_is_readable() throws Throwable {
inputStream = new FileInputStream(file);
String fileExtensionName = filename.substring(filename.indexOf("."));
}
#Then("^Read The Excel$")
public void read_the_excel() throws Throwable {
RegExcel = new XSSFWorkbook(inputStream);
RegExcelSheet = RegExcel.getSheet("Sheet1");
}
#And("^Create Array For Dates Data In Excel$")
public void create_array_for_dates_data_in_excel() throws Throwable {
rowCount = RegExcelSheet.getLastRowNum()-RegExcelSheet.getFirstRowNum();
excelDataValue = new String[rowCount+1][5];
for (int i = 0; i < rowCount+1; i++)
{
row = RegExcelSheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++)
{
excelDataValue[i][j]=row.getCell(j).toString();
//System.out.println(row.getCell(j).toString());
}
}
}

I want to know, why get a exception of redis.clients.jedis.exceptions.JedisConnectionException?

I used jedis in my java project with one master and slave, once the slave started, it come to this in redis_slave.log:
44764 [2721] 24 Dec 14:07:41.157 * Connecting to MASTER...
44765 [2721] 24 Dec 14:07:41.158 * MASTER <-> SLAVE sync started
44766 [2721] 24 Dec 14:07:41.158 # Error condition on socket for SYNC: Connection refused
and in my java source file, I want to delete all data in redis, so I wrote this code:
public class TestJedisPool {
private Jedis jedis = null;
private JedisPool jedisPool = null;
public TestJedisPool() {
initialPool();
jedis = jedisPool.getResource();
jedis.auth("123456");
}
private void initialPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(20);
config.setMaxIdle(5);
config.setMaxWait(1000L);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config, "192.168.144.3", 6397);
}
private void masterThread() {
System.out.println(jedis.flushAll());
jedisPool.returnResource(jedis);
jedis.disconnect();
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
}
}
and get a exception like this:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:22)
at com.oppo.testpool.TestJedisPool.<init>(TestJedisPool.java:15)
at com.oppo.testpool.TestJedisPool.main(TestJedisPool.java:41)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
any one can help me ?
I modified your code and it works for:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class TestJedisPool {
static ExecutorService executor = Executors.newSingleThreadExecutor();
final static ShardedJedisPool redisStatsPool;
static {
String host = "127.0.0.1";
int port = 6379;
List<JedisShardInfo> redisClickShard = new ArrayList<JedisShardInfo>();
redisClickShard.add(new JedisShardInfo(host, port));
JedisPoolConfig config = new JedisPoolConfig();
config.maxActive = 1000;
config.maxIdle = 10;
config.minIdle = 1;
config.maxWait = 30000;
config.numTestsPerEvictionRun = 3;
config.testOnBorrow = true;
config.testOnReturn = true;
config.testWhileIdle = true;
config.timeBetweenEvictionRunsMillis = 30000;
redisStatsPool = new ShardedJedisPool( config, redisClickShard);
}
public TestJedisPool() {
}
String[] getRandomNumber(int min, int max){
String[] test = new String[8];
for (int i = 0; i < test.length; i++) {
int partition = min + (int)(Math.random() * ((max - min) + 1));
test[i] = "key"+partition;
}
return test;
}
static volatile long sum = 0;
public Runnable hincrBy(final String keyname, final String[] keyfields , final long val){
Runnable job = new Runnable() {
#Override
public void run() {
c++;
System.out.println(c);
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Pipeline p = jedis.pipelined();
for (String keyfield : keyfields) {
p.hincrBy(keyname, keyfield, val);
sum += val;
}
p.sync();
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
}
};
return job;
}
static volatile int c = 0;
static final int MAX = (int) Math.pow(10, 6);
void masterThread() {
for (int i = 0; i < MAX; i++) {
String[] keynames = getRandomNumber(100, 1000);
executor.submit(hincrBy("test10^6", keynames, 1L));
}
executor.shutdown();
while(!executor.isTerminated()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int sumTest() {
int total = 0;
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Map<String,String> map = jedis.hgetAll("test10^6");
Set<String> keys = map.keySet();
for (String keyfield : keys) {
int v = Integer.parseInt(map.get(keyfield));
total += v;
}
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
return total;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
System.out.println(sum);
System.out.println(test.sumTest());
System.out.println(test.sumTest() == sum);
}
}

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

SSL Server Exception: javax.net.ssl.SSLException

I am creating a SSL Server and Client in Java. The point of the program is to mimic a movie theater program. I can establish the connection but when I attempt to "reserve" a seat the program crashes. I get the following error:
Server aborted: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is my Server Code
// SSL Server
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class SSL_Server {
public static void main(String[] args) {
int port = 2018;
System.setProperty("javax.net.ssl.keyStore","mySrvKeystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = null;
System.out.println("SSL_Server started");
final ExecutorService threadPool = Executors.newCachedThreadPool();
try {
ssocket = ssocketFactory.createServerSocket(port);
InetAddress myIP =InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());
while(true){
Socket aClient = ssocket.accept();
//create a new thread for every client
threadPool.submit(new SSL_ClientHandler(aClient));
}
}
catch(Exception e) {
System.err.println("Server aborted:" + e);
} finally {
try{
ssocket.close();
} catch (Exception e){
System.err.println("could not close connection properly" + e);
}
}
System.out.println("connection was closed successfully");
}
}
The following is my client code
//SSL Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class TCP_Client {
public static void main(String[] args) throws IOException{
// SSL_Client newClient = new SSL_Client();
// Lock lock = new ReentrantLock();
boolean validInput = false;
BufferedReader din;
PrintStream pout;
int port = 2018;
BufferedReader stdinp = new BufferedReader(new InputStreamReader(System.in));
String line = "done";
StringTokenizer st;
String hostname;
String task = "done";
if(args.length>0)
hostname = args[0];
else
hostname = "localhost";
SocketFactory socketFactory = SSLSocketFactory.getDefault();
//Socket socket = socketFactory.createSocket(hostname, port);
while(true)
{
try{
//read input
while(!validInput)
{
System.out.println("Please enter a valid command or 'done' to finish.");
line = stdinp.readLine();
st = new StringTokenizer(line);
task = st.nextToken();
if(task.equals("reserve") || task.equals("search") || task.equals("delete") || task.equals("getinfo") || task.equals("done"))
{
validInput =true;
break;
}
System.out.println("Invalid command. Please enter another command or 'done' to escape.");
}
if(task.equals("done"))
{
break;
}
validInput = false;//reset for next line read in
//create a new socket every time
//Socket socket = new Socket(hostname, port);
Socket socket = socketFactory.createSocket(hostname, port);
din = new BufferedReader (new InputStreamReader (socket.getInputStream()));
pout = new PrintStream (socket.getOutputStream());
pout.println(line);
pout.flush();
//print out response from server
System.out.println(din.readLine());
} catch (Exception e){
System.err.println("Server aborted: " + e);
}
}
}
}
"Unable to find valid certification path to requested target" means that your truststore doesn't trust the server certificate. Import it into your truststore, or have it signed by a recognized CA.