Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Connection refused" error on socket_connect in php

Tags:

php

sockets

perl

I am trying to convert some code from perl to php.

Perl code looks like below:

my $handle = Connect($port, $host);

and I am trying to use socket to do the same thing in php. I have tried socket_create and socket_connect, socket_create and socket_bind, and fsocketopen.

As a result, I'm stuck with error messages saying "Connection refused" or "permission denied":

socket_connect() [function.socket-connect]: unable to connect [111]: Connection refused in

I am not sure if this is the problem I need to solve, or the problem of permission because the code in perl works fine (I did not write that code).

my php code looks like below:

$socket =  socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$socket){
        die('Error: socket_create()');
}
if(!socket_connect($socket,$host,$port)) {
        die('Error: socket_connect()');
}

I'm not the one who manages the server, so I will need to ask someone else for the access if it is a permission issue. What should I ask for specifically?

Or should I use some other function to connect to the server? I am new to perl, so I am not sure if socket_connect is the equivalent function to use or not.

Thanks.

like image 386
user1507925 Avatar asked Oct 07 '22 07:10

user1507925


1 Answers

If your perl code is able to establish the connection, no additional permissions should be needed to do the same in php. Connection refused means the remote host doesn't let you in (you probably connect to wrong address/port). Permission denied is more surprising, a lot of people have this kind of problem while running httpd scripts with SELinux enabled. If you're one of them, refer to the SELinux manpage:

SELinux policy can be setup such that httpd scripts are not allowed to connect out to the network. This would prevent a hacker from breaking into you httpd server and attacking other machines. If you need scripts to be able to connect you can set the httpd_can_network_connect boolean on:

setsebool -P httpd_can_network_connect 1

I have a few concers to your examples though. Connect from your Perl snippet doesn't seem to be the standard socket connect; I don't know which module it belongs to, but are you sure there is no magic behind the call? As socket_connect takes address in dotted-quad notation (for IPv4), make sure you're not passing a hostname (you would need to make a DNS lookup first). At the very end check if it's really a TCP socket you need, not UDP.

like image 166
tomasz Avatar answered Oct 13 '22 09:10

tomasz