yet another java problem ...
got a client which should connect to a server via passive mode.
it seems to work fine, i get the ip adress and the port and the passivesocket says that it's ready.
but the passivesocket.getInputStream isn't ready at all - so i can't read from it and don't get the response to LIST.
can't figure out why, any suggestions?
public synchronized void getPasvCon() throws IOException, InterruptedException {
// Commands abholen
// IP Adresse holen
Thread.sleep(200);
String pasv = commands.lastElement();
String ipAndPort = pasv.substring(pasv.indexOf("(") + 1,
pasv.indexOf(")"));
StringTokenizer getIp = new StringTokenizer(ipAndPort);
// holt die IP
String ipNew = ""; // IP für den neuen Socket
for (int i = 0; i < 4; i++) {
if (i < 3) {
ipNew += (getIp.nextToken(",") + ".");
} else {
ipNew += (getIp.nextToken(","));
}
}
Integer portTemp1 = new Integer( getIp.nextToken(","));
Integer portTemp2 = new Integer (getIp.nextToken(","));
portNew = (portTemp1 << 8 )+ portTemp2;
System.out.println(">>>>> " + ipNew + ":" + portNew);
try {
pasvSocket = new Socket(ipNew, portNew);
System.out.println("Socket verbunden: "+ pasvSocket.isConnected());
} catch (UnknownHostException e) {
System.out.println("Host unbekannt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fromPasvServer = new BufferedReader(new InputStreamReader(
pasvSocket.getInputStream()));
Thread.sleep(2000);
System.out.println("Streams bereit: " + fromPasvServer.ready() + " | " );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writePasvCommands = new PrintWriter(pasvSocket.getOutputStream(),
true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(3000);
Thread pasvKonsole = new Thread(new PasvKonsole(this));
pasvKonsole.start();
}
public void LIST() throws IOException {
writeCommands.print("LIST\n");
writeCommands.flush();
}
public void run() {
try {
connect();
// getStatus();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
USER();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PASS();
try {
Thread.sleep(2000);
PASV();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.io.IOException;
public class PasvKonsole extends Thread {
Client client;
public PasvKonsole(Client client) {
this.client = client;
}
public void run() {
System.out.println("========= PasvKonsole started");
while(true) {
try {
String lineP = client.fromPasvServer.readLine();
System.out.println("***" + lineP);
System.out.println("Ich bin da und tue auch was");
} catch (IOException e) {}
}
}
}
Added a Thread.Sleep and it works.
Related
I need to limit the number of client that can connect to the server . I only want 3 clients that can connect not more.
I tried if else conditions. and some loops.
public class server {
ServerSocket ss;
boolean quite=false;
ArrayList<MultiServerConnection> OurDomainsConnections=new ArrayList<MultiServerConnection>();
public static void main(String[] args) {
new server();
}
public server() {
try {
//TODO use method to take this as an input from user)
ss=new ServerSocket(3333);//here we are using connection 3333 (change as you want
while(!quite)
{
Socket s=ss.accept();//when a connection to the domain is found we accept it
MultiServerConnection OurConnection = new MultiServerConnection(s,this);
OurConnection.start();//Start Thread
OurDomainsConnections.add(OurConnection);//add connection to our Domain Connection
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//make sure its bloody same with client it took my 15 min to realize that XD
}
}
public class MultiServerConnection extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
server ss;
boolean quite=false;
public MultiServerConnection(Socket OurSocket,server OurServer)
{
super("MultiServerConnection");//server connection thread
this.s=OurSocket;
this.ss=OurServer;
}
public void ServerOutClientIn(String OutText)
{
try {
long ThreadID=this.getId();
dout.writeUTF(OutText);
dout.flush();//this is because of a buffer error :<
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void ServerOutAllClientIn(String OutText)
{
for(int i=0;i<ss.OurDomainsConnections.size();i++)
{
MultiServerConnection Connection=ss.OurDomainsConnections.get(i);
Connection.ServerOutClientIn(OutText);
}
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
while(din.available()==0)
{
try {
Thread.sleep(1);//sleep if there is not data coming
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String ComingText=din.readUTF();
ServerOutAllClientIn(ComingText);
}
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class MultiClients extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
boolean quite=false;
public ClientData c;
public interface1 GUI;
public MultiClients(Socket OurMultiSocket, interface1 gui)
{
s=OurMultiSocket;
c=new ClientData();
GUI=gui;
}
public void ClientOutServerIn(String Text)
{
//write the line from console to server
try {
if(Text.equals("change channel"))
{
System.out.print("sending changing channel: "+Text+"\n");
dout.writeUTF(Text);
dout.flush();
}
else if(Text.equals("new user"))
{
System.out.print("sending new user: "+ Text+"\n");
dout.writeUTF(Text+":"+c.GetName()+"="+c.GetChannel());
dout.flush();
}
else
{
dout.writeUTF(c.GetChannel()+"="+this.getName()+": "+Text);
dout.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SetClient(String channel,String Name)
{
c.SetName(Name);
c.SetChannel(channel);
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
try {
while(din.available()==0)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//if there is something just show it on console
//and then go back and do the same
String reply=din.readUTF();
String Chan=ExtractChannel(reply);
String name=ExtractName(reply);
/*if (reply.equals("change channel"))
{
System.out.print("changing channel in body: "+reply+"\n");
//GUI.ClearDisplay();
setChangedChannel();
}*/
if(name.equals("new user"))
{
System.out.print("new user in body: "+reply+"\n");
//GUI.ClearDisplay();
setChannel(reply);
}
else
{
PrintReply(Chan,reply);
}
//System.out.println(reply);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
din.close();
dout.close();
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
din.close();
dout.close();
s.close();
} catch (IOException x) {
// TODO Auto-generated catch block
x.printStackTrace();
}
}
}
public void CloseClient()
{
try {
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ExtractName(String x)
{
String[]Y=x.split(":");
return Y[0];
}
public String ExtractChannel(String X)
{
String[]Y=X.split("=");
return Y[0];
}
public void PrintReply(String Chan,String Rep)
{
if(c.GetChannel().equals(Chan))
{
String []Y=Rep.split("=");
GUI.setDisplay(Y[1]);
//System.out.println(Y[1]+"\n \n \n \n");
}
}
public void setChannel(String x)
{
String []Y=x.split(":");
String []Z=Y[1].split("=");
System.out.print("setting "+Z[0]+" channel to "+Z[1]+"\n");
GUI.setUserInChannel(Z[0]);
}
public void setChangedChannel()
{
GUI.setUserInChannel(c.GetName()+": "+c.GetChannel());
}
class ClientData
{
public String ClientName;
public String channel;
public void SetChannel(String Chan)
{
channel=Chan;
}
public void SetName(String name)
{
ClientName=name;
}
public String GetChannel()
{
return channel;
}
public String GetName()
{
return ClientName;
}
}
}
in this code. more than 5 user can can chat together. i only want to allow 3 user to connect and to chat.
You can use AtomicInteger as a counter to check how many clients you have already connected:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class server {
ServerSocket ss;
boolean quite=false;
ArrayList<MultiServerConnection> OurDomainsConnections=new ArrayList<MultiServerConnection>();
final AtomicInteger runningCount = new AtomicInteger(0);
final Integer limit = 3;
public static void main(String[] args) {
new server();
}
public server() {
try {
//TODO use method to take this as an input from user)
ss=new ServerSocket(3333);//here we are using connection 3333 (change as you want
while(!quite)
{
Socket s=ss.accept();//when a connection to the domain is found we accept it
if (runningCount.incrementAndGet() < limit){ //increment number of clients and check
MultiServerConnection OurConnection = new MultiServerConnection(s,this, runningCount::decrementAndGet);
OurConnection.start();//Start Thread
OurDomainsConnections.add(OurConnection);//add connection to our Domain Connection
} else {
runningCount.decrementAndGet();
s.close();
System.out.println("limit exceeded");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//make sure its bloody same with client it took my 15 min to realize that XD
}
}
interface Callback {
void call();
}
class MultiServerConnection extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
server ss;
boolean quite=false;
final Callback callbackOnFinish;
public MultiServerConnection(Socket OurSocket,server OurServer, Callback callbackOnFinish)
{
super("MultiServerConnection");//server connection thread
this.s=OurSocket;
this.ss=OurServer;
this.callbackOnFinish = callbackOnFinish;
}
public void ServerOutClientIn(String OutText)
{
try {
long ThreadID=this.getId();
dout.writeUTF(OutText);
dout.flush();//this is because of a buffer error :<
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void ServerOutAllClientIn(String OutText)
{
for(int i=0;i<ss.OurDomainsConnections.size();i++)
{
MultiServerConnection Connection=ss.OurDomainsConnections.get(i);
Connection.ServerOutClientIn(OutText);
}
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
while(din.available()==0)
{
try {
Thread.sleep(1);//sleep if there is not data coming
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String ComingText=din.readUTF();
ServerOutAllClientIn(ComingText);
}
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
callbackOnFinish.call();
}
}
}
When a new connection is accepted runningCount is atomically increased and value is got by runningCount.incrementAndGet(). Then if value below the limit - new MultiServerConnection is created with a callback. The callback is used for decrementing a counter on exit. If counter equal or above the limit => socket will be closed and error message printed. It is good to have a message passed to the socket.
P.S. I have not reviewed your solution. I've just added the feture you requested.
i am trying to generate a snapshot from a video using the following code. and it is working fine running as a java application on sts.
public class VideoThumbTaker {
public static void main(String[] args)
{
FFmpegFrameGrabber g = new FFmpegFrameGrabber("/home/anupam/Downloads/jk.mp4");
g.setFormat("mp4");
try {
g.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0 ; i < 1 ; i++) {
try {
ImageIO.write(g.grab().getBufferedImage(), "png", new File("/home/anupam/Downloads/" + System.currentTimeMillis() + ".png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
g.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
using maven dependency
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>0.8</version>
</dependency>
after deploying a war file.the following code gives Error loading class org/bytedeco/javacpp/Loader
#RequestMapping(value = "menu9data", method = RequestMethod.POST)
public JSONObject view(#RequestPart(name = "file", required = false) MultipartFile image,#Valid MenuData model, BindingResult results) {
String name1;
FFmpegFrameGrabber g = new FFmpegFrameGrabber("/home/anupam/Downloads/"+name1); //Error
g.setFormat("mp4");
try {
System.out.println("enterss");
g.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0 ; i < 1 ; i++) {
/* try {
// ImageIO.write(((Object) g.grab()).getBufferedImage(), "png", new File("/home/anupam/Downloads/"+name1+"snap"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
try {
g.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using vmware API. By using this API I am able to get information of ESX devices. Now I want to get information about vcenter using this API, but get exception "Java.rmi.remoteException: VI SDK Invoke exception : javax.net.ssl.SSLHandShakeException: java.security."
Here is a code:
public void realesx(){
System.out.println("Running ESX Realtime for host ..."+host);
JSONObject esxcmdout = new JSONObject();
String url = "https://" + host + "/sdk/vimService";
try {
ServiceInstance si = new ServiceInstance(new URL(url), user, pass,true);
System.out.println("host :"+host+"---"+si.getAboutInfo().getFullName());
System.out.println(" Version is .. " +si.getAboutInfo().version);
System.out.println(" os type is .. " +si.getAboutInfo().osType);
System.out.println("Vendor is .. " + si.getAboutInfo().vendor);
System.out.println("name is" + si.getAboutInfo().name);
try{
esxcmdout.put("vmWayerVersion", si.getAboutInfo().version);
esxcmdout.put("vmWayerOSType", si.getAboutInfo().osType);
esxcmdout.put("vmWayerVendor", si.getAboutInfo().vendor);
esxcmdout.put("vmWayerName", si.getpublic void realesx(){
System.out.println("Running ESX Realtime for host ..."+host);
JSONObject esxcmdout = new JSONObject();
String url = "https://" + host + "/sdk/vimService";
try {
ServiceInstance si = new ServiceInstance(new URL(url), user, pass,true);
System.out.println("host :"+host+"---"+si.getAboutInfo().getFullName());
System.out.println(" Version is .. " +si.getAboutInfo().version);
System.out.println(" os type is .. " +si.getAboutInfo().osType);
System.out.println("Vendor is .. " + si.getAboutInfo().vendor);
System.out.println("name is" + si.getAboutInfo().name);
try{
esxcmdout.put("vmWayerVersion", si.getAboutInfo().version);
esxcmdout.put("vmWayerOSType", si.getAboutInfo().osType);
esxcmdout.put("vmWayerVendor", si.getAboutInfo().vendor);
esxcmdout.put("vmWayerName", si.getAboutInfo().name);
}
catch (Exception e){
e.printStackTrace();
}
ManagedEntity[] managedEntities = new InventoryNavigator(
si.getRootFolder()).searchManagedEntities("VirtualMachine");
ManagedEntity[] hostmanagedEntities = new InventoryNavigator(
si.getRootFolder()).searchManagedEntities("HostSystem");
for (ManagedEntity hostmanagedEntity : hostmanagedEntities) {
HostSystem hostsys = (HostSystem) hostmanagedEntity;
String ESXhostname = hostsys.getName();
//System.out.println("main system version is .. " + hostsys.getConfig());
HostListSummary hls = hostsys.getSummary();
HostHardwareSummary hosthwi = hls.getHardware();
HostListSummaryQuickStats hqs = hls.getQuickStats();
Datastore[] HDS = hostsys.getDatastores();
StringBuilder DS = new StringBuilder();
for (int i=0;i <HDS.length;i++){
DatastoreSummary dsm =HDS[i].getSummary();
DS.append(dsm.name+":"+dsm.capacity+":"+dsm.freeSpace+"-");
}
int MEM=hqs.overallMemoryUsage;
int UPT=hqs.getUptime();
Integer CPU=hqs.getOverallCpuUsage();
String esxkey = "ESXRealInfo";
String esxvalue = "ESXhostname-" + ESXhostname
+ ";CPU Usage-" + CPU + ";MEM Usage-"
+ MEM + ";UPTIME-" + UPT+"; Datastores -"+DS;
try {
esxcmdout.put(esxkey, esxvalue);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < managedEntities.length; i++) {
VirtualMachine vm = (VirtualMachine) managedEntities[i];
String vmName = vm.getName();
String vmIP = vm.getGuest().getIpAddress();
VirtualMachineConfigInfo config = vm.getConfig();
VirtualHardware hw = config.getHardware();
String vmVersion = config.version;
System.out.println("######### vm version is ###### ... "+ vmVersion);
int vmCPU = hw.getNumCPU();
int vmMem = hw.getMemoryMB();
String vmkey = "vm" + i;
String vmvalues = "Name-" + vmName + ";IP-" + vmIP + ";vmCPU-"
+ vmCPU + ";vmMem-" + vmMem + ";vmVersion-" + vmVersion;
System.out.println("string to write is... "+vmvalues);
try {
esxcmdout.put(vmkey, vmvalues);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
si.getServerConnection().logout();
}
catch (InvalidProperty e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
runMT.httpput(runtype, host, vmwtype, esxcmdout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}AboutInfo().name);
}
catch (Exception e){
e.printStackTrace();
}
ManagedEntity[] managedEntities = new InventoryNavigator(
si.getRootFolder()).searchManagedEntities("VirtualMachine");
ManagedEntity[] hostmanagedEntities = new InventoryNavigator(
si.getRootFolder()).searchManagedEntities("HostSystem");
for (ManagedEntity hostmanagedEntity : hostmanagedEntities) {
HostSystem hostsys = (HostSystem) hostmanagedEntity;
String ESXhostname = hostsys.getName();
//System.out.println("main system version is .. " + hostsys.getConfig());
HostListSummary hls = hostsys.getSummary();
HostHardwareSummary hosthwi = hls.getHardware();
HostListSummaryQuickStats hqs = hls.getQuickStats();
Datastore[] HDS = hostsys.getDatastores();
StringBuilder DS = new StringBuilder();
for (int i=0;i <HDS.length;i++){
DatastoreSummary dsm =HDS[i].getSummary();
DS.append(dsm.name+":"+dsm.capacity+":"+dsm.freeSpace+"-");
}
int MEM=hqs.overallMemoryUsage;
int UPT=hqs.getUptime();
Integer CPU=hqs.getOverallCpuUsage();
String esxkey = "ESXRealInfo";
String esxvalue = "ESXhostname-" + ESXhostname
+ ";CPU Usage-" + CPU + ";MEM Usage-"
+ MEM + ";UPTIME-" + UPT+"; Datastores -"+DS;
try {
esxcmdout.put(esxkey, esxvalue);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < managedEntities.length; i++) {
VirtualMachine vm = (VirtualMachine) managedEntities[i];
String vmName = vm.getName();
String vmIP = vm.getGuest().getIpAddress();
VirtualMachineConfigInfo config = vm.getConfig();
VirtualHardware hw = config.getHardware();
String vmVersion = config.version;
System.out.println("######### vm version is ###### ... "+ vmVersion);
int vmCPU = hw.getNumCPU();
int vmMem = hw.getMemoryMB();
//sasSystem.out.println(vmName + vmIP + vmCPU + vmMem);
String vmkey = "vm" + i;
String vmvalues = "Name-" + vmName + ";IP-" + vmIP + ";vmCPU-"
+ vmCPU + ";vmMem-" + vmMem + ";vmVersion-" + vmVersion;
System.out.println("string to write is... "+vmvalues);
try {
esxcmdout.put(vmkey, vmvalues);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
si.getServerConnection().logout();
}
catch (InvalidProperty e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
runMT.httpput(runtype, host, vmwtype, esxcmdout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code works fine for collecting information of ESX devices.
How do I resolve error of certificate for vcenter?
Is there any alternative way to do this?
You have to import the certificate so go through this vSphere_Documentation page to know import certificates.
edit:
try the given below code and have a look at this answer
KeyStore keyStore = KeyStore.getInstance("JKS");
String fileName = "D:\\certs_path\\cacerts"; // cerrtification file path
System.setProperty("javax.net.ssl.trustStore", fileName);
try changing the last argument on the ServiceInstance to false like this: ServiceInstance si = new ServiceInstance(new URL(url), user, pass,false);
I have desktop and android applications, which connected by bluetooth(in desktop side I use Bluecove 2.1.1 library). Desktop application create bluetooth service then android application connects to it. I want to add logout functionality from both desktop and android sides. For example in desktop app user click disconnect, both desktop and android apps reset their connections and should be able to connect again. Here is bluetoothService code for desktop side:
public class BluetoothService
{
private static final String serviceName = "btspp://localhost:"
// + new UUID("0000110100001000800000805F9B34F7", false).toString()
// + new UUID("0000110100001000800000805F9B34F8", false).toString()
+ new UUID("0000110100001000800000805F9B34F9", false).toString()
+ ";name=serviceName";
private StreamConnectionNotifier m_service = null;
private ListenerThread m_listenerThread;
private DataOutputStream m_outStream;
public BluetoothService()
{
Open();
}
public void Open()
{
try
{
assert (m_service == null);
m_service = (StreamConnectionNotifier) Connector.open(serviceName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Start()
{
try
{
StreamConnection connection = (StreamConnection) m_service
.acceptAndOpen();
System.out.println("Connected");
m_listenerThread = new ListenerThread(connection);
Thread listener = new Thread(m_listenerThread);
listener.start();
m_outStream = new DataOutputStream(connection.openOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Send(String message)
{
assert (m_listenerThread != null);
try
{
m_outStream.writeUTF(message);
m_outStream.flush();
System.out.println("Sent: " + message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Close()
{
try
{
m_service.close();
m_listenerThread.Stop();
m_listenerThread = null;
m_outStream.close();
m_outStream = null;
m_service = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ListenerThread implements Runnable
{
private DataInputStream m_inStream;
private boolean m_isRunning;
public ListenerThread(StreamConnection connection)
{
try
{
this.m_inStream = new DataInputStream(connection.openInputStream());
m_isRunning = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
;
}
public void run()
{
while (m_isRunning)
{
try
{
assert (m_inStream != null);
if (m_inStream.available() > 0)
{
String message = m_inStream.readUTF();
System.out.println("Received command: " + message);
CommandManager.getInstance().Parse(message);
}
}
catch (IOException e)
{
System.err.println(e.toString());
}
}
}
public void Stop()
{
m_isRunning = false;
try
{
m_inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for restarting service I do:
BluetoothService::Close();
BluetoothService::Open();
BluetoothService::Start();
but seems I cannot reconnect. Maybe I should create service with different name?
I wrote a server in java that is on port 4444.
Then I made a mysql connection with terminal to port 4444(my mysql real port is 3306)
Then with jpcap I captured the packet and changed the src port and ip to my server port and ip and also I changed destination port and id to mysql port and ip.
and I send the new packet with jpcapSender. The problem is that when I send the packet the length of that is 74. but when I capture that packet it is 60 bytes. I guessed it is because the dont_frag is false. But changing it didn't help.
package connection;
public class Bridge implements PacketReceiver {
NetworkInterface device;
static int DeviceName;
public Bridge(NetworkInterface device,int deviceName) throws IOException {
ServerSocket ss = new ServerSocket(4444);
this.device = device;
this.DeviceName=deviceName;
System.err.println(DeviceName);
JpcapCaptor jpcap;
jpcap = JpcapCaptor.openDevice(device, 2000, false, 20);
// System.err.println(jpcap.isNonBlockinMode());
jpcap.loopPacket(-1, new Bridge());
}
public Bridge() {
}
#Override
public void receivePacket(Packet p) {
if (p instanceof TCPPacket) {
TCPPacket myPacket = (TCPPacket) p;
if(myPacket.dst_port==3306 && myPacket.src_port==4444){
System.err.println("don't frag"+myPacket.len);
}
if (myPacket.dst_port == 4444) {
if(myPacket.syn==true){
System.err.println("connecting"+myPacket.len);
DatalinkPacket dlp=myPacket.datalink;
System.err.println(dlp.toString());
try {
Server.src_ip = myPacket.src_ip;
Server.src_port = myPacket.src_port;
myPacket.src_ip = InetAddress.getByName("127.0.0.1");// TODO
// variable
myPacket.src_port = 4444;
myPacket.dst_ip = InetAddress.getByName("127.0.0.1");// System.err.println("device"+this.DeviceName);
myPacket.dst_port = 3306;
sendPacket(myPacket);
} catch (UnknownHostException e) {
// Auto-generated catch block
e.printStackTrace();
}//
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (myPacket.syn = false ) {//
System.err.println("query request");
MySqlRequestParser parser = new MySqlRequestParser(
myPacket.data);
String query = parser.getQuery();
System.err.println(query);
// TODO get rules from db
// TODO check for rules
try {
Server.src_ip = myPacket.src_ip;
Server.src_port = myPacket.src_port;
// myPacket.src_ip = InetAddress.getByName("127.0.0.1");// TODO
// variable
//myPacket.src_port = 4444;
myPacket.dst_ip = InetAddress.getByName("127.0.0.1");// TODO
myPacket.dst_port = 3306;
sendPacket(myPacket);
} catch (UnknownHostException e) {
// Auto-generated catch block
e.printStackTrace();
}//
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (myPacket.src_port == 3306) {
System.err.println("response"+myPacket.sequence);
if (myPacket.syn == false || myPacket.syn == true) {
System.err.println("response to query");
myPacket.dst_ip = Server.src_ip;
myPacket.dst_port = Server.src_port;
myPacket.src_port = 4444;// TODO about ip it's kinda
// fishiiii
try {
sendPacket(myPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public void sendPacket(TCPPacket packet) throws IOException {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
System.err.println("dev number"+DeviceName);
NetworkInterface dev=devices[DeviceName];
System.err.println("in sender packet src ip"
+ packet.src_ip.getHostAddress() + " dst ip "
+ packet.dst_ip.getHostAddress() + " src port "
+ packet.src_port + " dst port " + packet.dst_port+" len"+packet.len+" datalink:"+packet.datalink.toString());
JpcapSender sender = JpcapSender.openDevice(dev);
//TCPPacket tp=new TCPPacket(packet.src_port,packet.dst_port, packet.sequence, packet.ack_num, packet.urg, packet.ack, packet.psh, packet.rst, packet.syn, packet.fin, packet.rsv1, packet.rsv2, packet.window, packet.urgent_pointer);
System.err.println("open device"+packet.len);
boolean df=packet.dont_frag;
boolean mf=packet.more_frag;
boolean rf=packet.rsv_frag;
packet.dont_frag=true;
packet.offset=(short)(((packet.offset&0xFF)<<8)|((packet.offset&0xF00)>>8));
packet.offset=(short)((packet.offset|((mf?0x0020:0)|(df?0x0040:0)|(rf?0x0080:0))));
System.err.println("don't frag"+packet.dont_frag);
sender.sendPacket(packet);
System.err.println("packet sent");
sender.close();
}
public static void main(String[] arg) throws IOException {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
int localIndex = 0;
for (int i = 0; i < devices.length; i++) {
if (devices[i].name.equals("lo")) {
localIndex = i;
}
}
System.err.println("lo:" + localIndex);
Bridge br = new Bridge(devices[localIndex],localIndex);
}
}