Ehsan Jeihani
Ehsan Jeihani

Reputation: 1258

why connection is refused while trying to use socket in PHP and android?

why i get java.net.ConnectException: /192.168.1.5:6789 - Connection refused?

i am using php and android java code. before asking this question i checked questions like java.net.ConnectException: Connection refused. while there were useful but they could not solve my problem.

the scenario is

1- i am using XAMPP

2- windows firewall is off

3- when i run php script i can see port 6789 is set to listening by checking netstat -a

4- java "android" code :

    try
        {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);//"192.168.1.5" the PC which XAMPP is runing on
            socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);//6789
        }
        catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }

5- php code

 <?php
set_time_limit( 0 );
$address = '127.0.0.1';
$port = 6789;
$sock = socket_create( AF_INET, SOCK_STREAM, 0 ); // 0 for  SQL_TCP
socket_bind( $sock, 0, $port ) or die( 'Could not bind to address' );  
socket_listen( $sock );
  while (true) {
    $client = socket_accept( $sock );
    $input = socket_read( $client, 1024000 );
    socket_write( $client, $response );
    socket_close( $client );
 }

socket_close( $sock );

6- i run php script and it keeps loading that mean it is listening and is in while block

7- i start the android app and i get this notification

java.net.ConnectException: /192.168.1.5:6789 - Connection refused

and finally i am sure that PC(server) IP address is correct and in manifests internet permission is set

thank you in advance!

Upvotes: 0

Views: 329

Answers (1)

Stephen C
Stephen C

Reputation: 718788

I don't think that socket_create( AF_INET, SOCK_STREAM, 0 ); is correct. The third number is the protocol number, and the documentation says that you should be using the SOL_TCP constant for that.

The value 0 is the protocol number for IP. The protocol number for TCP is 6. Both of these are according to "/etc/protocols" on my Linux machine ... which is the definitive source according to the documentation / comments for socket_create and getprotobynumber.

Upvotes: 1

Related Questions