Android client can't open a socket to a C server - java

I couldn't find anything about this quite specific problem, but maybe someone else has done this.
I have a server program written in C (error checking removed for readability):
int main(int arc, char *argv[])
{
int sockfd, newsockfd, portnum, cli_len, num_chars, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
// Set up the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Set up our variables
bzero((char *) &serv_addr, sizeof(serv_addr));
portnum = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portnum); // Convert from host port to network port
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("Socket could not be bound");
listen(sockfd, 5); // Get ready to receive connections
cli_len = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &cli_len);
// Message processing
return 0;
}
Meanwhile, I have the Android client (Version 4.1.2):
private class ClientTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
InetAddress a = InetAddress.getByAddress(new byte[] {(byte) 192, (byte) 168, 1, (byte) 102});
sock = new Socket(a, 65053);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
// Message processing
} catch (UnknownHostException e) {
System.out.println("No address found for ");
} catch (IOException e) {
System.out.println("Failed to open socket");
}
return null;
}
}
The issue I have is that the socket can't be opened by the Android client. I always get "Failed to open socket" after the timeout. The android client works with a java server I have, and a java client I have at least makes the connection with the C server. I don't understand what could be wrong...
If you need more details or additional code, let me know.

You don't specify if you're running both devices (server and client) just under the same LAN, in which case you can discard connectivity problems. If not, this might be a test. If you're able to connect your client to your server under the same router, that means that otherwise (i.e., using your public IPs) there's something blocking it, probably your router. Another issues could be antiviruses, OS ports blocking, router ports blocking...
If you're not able to connect both either under the same router connection, definitely it's a code issue. As you don't know where the culprit is, I'd suggest putting several Log.d() lines within the client code and printf() statements within the server code in the connectivity snippets on both sides and see where the bottleneck is, or use some debugging tool and put some breakpoints.
---- EDIT ----
Try connecting this way:
Socket socket;
final String host = "192.168.1.X";
final int port = 65053;
final int timeout = 30000; // 30 seconds
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("Sock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("Sock", "After a reasonable amount of time, I'm not able to connect!");
}
catch (IOException ioe) {
Log.e("Sock", "Hmmm... Sudden disconnection, probably you should start again!");
}

Whelp, it was a firewall issue, embarrassingly enough. Apparently Eclipse was let through my firewall, which is why the Java server worked, but I must've missed the prompt when I ran my C code through the command line. I disabled my firewall and it worked immediately.

Related

A socket with c server over java socket

My assignment requiers me to write an server in c but client in java. I need to send some integer to my client as instructions. They can connected smoothly but my java client cannot Receive the integer send from c server. there is only two possibilities: my c server did not send the Number out OR my client does not Receive the integer correctly. The c server is able to loop as I type in since the printf and scanf is executed while nothing happends on the client side.
I am stuck here, any help will be appreciate!
=========================================================================
UPDATE:
I correct the main class in java where the class name of the client into dotClient, and my client was able to conncected and read the inputs from the server.
I have try to send an 'int' directly in the server side, but When the client(java) use DataInputStream.ReadInt(), it returns a randomly big number as if the size of int in c and size of int in java is not matched.When I use a c client to do the same job, it works normal. So there is Hidden Problem for using dataInputStream directly with a c server, as I tried readShort() and ReadLong() as well.
As suggested, I use bufferReader.
And send string in server side, and perse it into int in client.
it works.
hère is my updated c code
#define PORT 55555
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024];
int returnSend = 0;
// Creating socket file descriptor
if (
(server_fd = socket(AF_INET, SOCK_STREAM, 0))
== 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
printf("%s\n", "Socket created!");
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET,
SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
printf("Socket attached!\n");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd,
(struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("socket binded!\n");
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
printf("socket listened!\n");
if ((new_socket = accept(server_fd,
(struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}// Socket formulated !
do{
fgets(buffer, sizeof(buffer), stdin);
returnSend = write(new_socket , buffer , strlen(buffer));
printf("Sending: %sReturn returnSend: %d.\n", buffer,returnSend);
} while (1);
return 0;
}
hère is my updated java client
import java.net.*;
import java.io.*;
public class dotClient
{
// initialize socket and input output streams
private Socket echoSocket= null;
private BufferedReader input = null;
// constructor to put ip address and port
public dotClient(String address, int port)
{
// establish a connection
try
{
echoSocket = new Socket(address, port);
System.out.println("Connected");
input =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
catch(UnknownHostException u)
{
System.out.println("exception 1: "+u);
}
catch(IOException i)
{
System.out.println("exception 2: "+i);
}
int number = 0;
String line = "";
// keep reading until read neagaive integer
try
{
while ((line = input.readLine()) != null)
{
number = Integer.parseInt(line);
System.out.println("String is :"+line);
System.out.println("number is :"+number);
}
}
catch(IOException i)
{
System.out.println("Exception 3: "+i);
}
// close the connection
try
{
input.close();
out.close();
echoSocket.close();
System.out.println("Connection closed!");
}
catch(IOException i)
{
System.out.println("Exception 4: "+i);
}
}
public static void main(String args[])
{
dotClient client = new dotClient("192.168.0.3", 55555);
}
}
In your main method you are creating a Client instance but your class is called dotClient. You might want to ensure you are creating an instance of your class dotClient. Otherwise I agree with the previous comments and would suggest BufferedReader and BufferedWriter/PrintWriter for the IO.
Do any of your try blocks catch an exception on the client? Check the return value of send(new_socket , &number , size(number) , 0 ); on the server to make sure the data was actually sent for more info checkout http://man7.org/linux/man-pages/man2/send.2.html.

Connect c++ unix server/socket to java windows client/socket

Initially I would like to thank you for your time...
I created a server socket in c++ in my macbook and a client/socket using Java in a diffrent machine which runs windows xp. I have specified the port to 5000 but I cant specify the correct Host and thus I can not make the connection. When I created a c++ server/socket in windows xp using WinSock2 the connection was made perfectly as I used the localhost...any ideas???
Thnx in advance
C++ code
int main( int argc, const char** argv )
{
/* SOCKET VARIABLES */
int sock;
struct sockaddr_in server;
int mysock;
char buff[1024];
int rval;
/*CREATE SOCKET*/
sock =socket(AF_INET, SOCK_STREAM, 0);
if (sock<0)
{
perror("*FAILED TO CREATE SOCKET*");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=5000;
/*CALL BIND*/
if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
{
perror("BIND FAILED");
exit(1);
}
/*LISTEN*/
listen(sock, 5);
/*ACCEPT*/
do{
mysock= accept(sock, (struct sockaddr *) 0, 0);
if (mysock==-1)
{
perror ("ACCEPT FAILED");
}
else
{
memset(buff, 0, sizeof(buff));
if ((rval=recv(mysock, buff, sizeof(buff), 0)) <0) {
perror("READING STREAM MESSAGE ERROR");
}
else if(rval==0)
printf("Ending connection");
else
printf("MSG: %s\n", buff);
printf("GOT THE MESSAGE (rval = %d)\n", rval);
}
return 0;
}while (1) ;
Java code
import java.io.;
import java.net.;
public class SOK_1_CLIENT {
public void run() throws Exception
{
Socket SOCK =new Socket ("localhost",5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
}
In java client, use the IP address of the system which is running server not "localhost". Localhost will refer to the local loopback address of the machine running the client code which is 127.0.0.1, but you have your server running on different machine, hence connection is not possible:
public void run() throws Exception
{
String address = "address_of_machine_running_server";
Socket SOCK =new Socket (address,5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
Also note that you need to set the firewall accordingly to allow the connections.
allow incoming and outgoing connections in both machine
check if ip address of your server is correct
try pinging the host(server) with its ip address to make sure that its up and working
if all the above returns positive, you will a have sucessfull connection.

Socket connectivity loss when sending live streaming data

I'm struggling here...
I'm trying to determine if data was successfully sent to the server through a TCP socket using the OutputStream object. For testing on emulator socket communications is loss after 30 sec. For write data OutputStream.write(); its doesn't throw an exception , and local server continuously running its not crashing, only tcp socket connection is loss after some time. All the methods in the socket class return as though the socket is active and working. Is there anything I'm doing wrong here? Is there any socket implementation or stream implementation I can use to get an exception or error when the stream/ socket doesn't actually send the data in the buffer? Also setting setSoTimeout() on the socket doesn't seem to do anything.
Please guide me...
Here is my code:
private void sendRec() {
int lstream;
int port = 1012;
byte[] byterecv = new byte[1040];
while (true) {
System.out.println("POOL-2");
synchronized (recSendThread) {
try {
recSendThread.wait(20);
} catch (InterruptedException e) {
}
}
if (stopcall == true) {
// break;
}
try {
// Provides a client-side TCP socket
Socket clientRec = new Socket();
// serverSocket = new ServerSocket(port);
// serverSocket.setSoTimeout(5000);
// Connects this socket to the given remote host address and
// port
clientRec.connect(new InetSocketAddress("192.168.1.36", port));
System.out.println("Just connected to "
+ clientRec.getRemoteSocketAddress());
System.out.println("SENTS Rec BEFORE");
// output streams that write data to the network
OutputStream outToServerRec = clientRec.getOutputStream();
DataOutputStream outStreamRec = new DataOutputStream(
outToServerRec);
outStreamRec.write(bData);
System.out.println("SENTS Rec AFTER");
// input streams that read data from network
InputStream inFromServerRec = clientRec.getInputStream();
// clientRec.setSoTimeout(5000);
DataInputStream inStreamRec = new DataInputStream(
inFromServerRec);
while ((lstream = inStreamRec.read(byterecv)) != -1) {
System.out.println("startrec bytearray -- "
+ byterecv.length);
bos1.write(byterecv, 0, lstream);
}
inStreamRec.close();// for closing dataouputstream
clientRec.close();// for closing socket connection
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my receiver and player code..
/**
* start receiving the voice data from server
* */
protected void startplay() {
System.arraycopy(frndid, 0, playByteData, 0, 4);
System.arraycopy(userid, 0, playByteData, 4, 4);
ByteBuffer.wrap(sessionid).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().
put(call_sessionid);
System.arraycopy(sessionid, 0, playByteData, 8, 4);
int lstream;
int port = 1014;
while (true) {
System.out.println("POOL-3");
try {
if (stopcall == true) {
System.out.println("BREAKEDDDD1111");
//break;
}
// Host name
// port++;
InetAddress addressPlay = InetAddress.getByName("192.168.1.36");
// Creates a new streaming socket connected to the target host
Socket clientPlay = new Socket(addressPlay, port);
System.out.println("Just connected to play : " +
clientPlay.getRemoteSocketAddress());
System.out.println("SENTS Play BEFORE");
// output streams that write data
OutputStream outToServer = clientPlay.getOutputStream();
DataOutputStream outStreamPlay = new DataOutputStream(outToServer);
outStreamPlay.write(playByteData);
System.out.println("SENTS Play after");
// input streams that read data
InputStream inFromServerPlay = clientPlay.getInputStream();
DataInputStream inStreamPlay = new DataInputStream(inFromServerPlay);
//clientPlay.setSoTimeout(5000);
while ((lstream = inStreamPlay.read(byteArray)) != -1) {
System.out.println("startplay() bytearray -- " +
byteArray.length);
bos.write(byteArray, 0, lstream);
}
inStreamPlay.close();
clientPlay.close();// for closing play socket connection
responseBuffer = bos.toByteArray();
System.out.println("BAOSSIZE " + bos.size());
bos.reset();
bos.flush();
bos.close();
playing = true;
System.out.println("res length -- " + responseBuffer.length);
rcvbb=ByteBuffer.wrap(responseBuffer).order(ByteOrder.LITTLE_ENDIAN).
asShortBuffer().get(playShortData);
playVoiceReceived();// plays received data
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* start playing received the voice data from server
* */
public void playVoiceReceived() {
System.out.println("POOL-4");
try {
if (at != null) {
if (at.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
at.play();// starts playing
} else {
System.out.println("Play BEFORE WRITE");
// Writes the audio data to the audio hardware for playback.
at.write(playShortData, 0, BufferElements2Play);
System.out.println("Play AFTER WRITE");
at.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The socket has sent the data ... to the local socket send buffer. What happens after that is up to the local TCP stack, the network, the remote TCP stack, and the remote application. If you want to know whether the remote application got the data, it will have to send you a reply.
Operator write does not check whether data was delivered because otherwise it would have to wait for too long time. If network connection is actually down, TCP layer of operating system, will try to send data anyway, but will detect problems somewhat later, i.e. 1 minute later, because it will not receive acknowledgement messages from the opposite side. It will then try to resend data several times, see that problem persists and only then will report exception condition on the socket. To know that socket is in exception condition, you need to perform some operator on socket, i.e. another write attempt. Try doing write in a loop like this:
while (true)
{
outStreamRec.write (data);
Thread.sleep (1000L);
}
It should throw an error about 2 minutes after network will be down.
Note, that in opposite to write operation, operation connect is synchronous, so it actually waits for response from the opposite side, and if there is not respose, it will throw an exception.

telneting ip/port in java/jsp

I'm trying to make a script that telnet ip port to see if the server is up or down. (like how you do in window command prompt. cmd [enter] => telnet 11.111.11.11 200 (ip& port)and if the the connection is successful, program will return true else false. I need this code to be really efficient since this function will go into the forloop where I do all the displays on the website for each ip. Thnx in advance
P.S
Ops I meant java/jsp my bad haha
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}

How to find which of the first 1024 ports seem to be hosting TCP based servers on a specified host?

I want to solve my problem using and I use java programming language.
Just try to connect to them with a Socket. If you don't get a ConnectException, something is listening st that TCP port. Then do the server a favor and close the socket immediately.
What's the purpose exactly?
This is a simple code to connect to a socket with a timeout
// Create a socket with a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
// Could not reach host - network error.
} catch (IOException e) {
// Network error
}
You can just run this code in a loop to check a series of ports.
NOTE: real portscanners are much more sophisticated: http://art-exploitation.org.ua/7261final/lib0021.html

Categories

Resources