Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Socket Connection Via Proxy

Tags:

php

proxy

sockets

I am working on an existing library, and i want it to establish connection to socket via proxy only. Current code is

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, "www.host.com", 8080);

Where i want this connection to be established via proxy (SOCK4/5)

I've Tried with

socket_bind($socket, '127.0.0.1', '9150');

Which is vidalia server, also I've tried some proxies from the internet which got working on firefox as sock but couldn't get this code connecting through it.

When i try putting above line i got following error.

Warning: socket_bind(): unable to bind address [10048]: Only one usage of each socket address (protocol/network address/port) is normally permitted.

like image 772
Ankit Pise Avatar asked Jul 06 '15 12:07

Ankit Pise


1 Answers

Don't want to offend you but it appears that you don't understand basics of TCP/IP networking. socket_ functions will not help you to deal with SOCKS proxy as they don't have SOCKS client.

Function socket_bind() is intended for setting source address for connection. Not for binding it to remote service. Basically you instruct your socket to appear as coming from 127.0.0.1:9150 and it complains as you probably have your SOCKS proxy running there. Even if you would have this address/port available it would not help: you just cannot connect from localhost anywhere else.

Only correct usage of socket_bind() is after socket_create() and before socket_connect() - after connection is established you cannot change source address.

Having this issue cleared let's get to your issue of having "establish connection to socket via proxy only". Honestly your question is really vague on details: what do you want to achieve? You need a stream or you just need to call some remote web server with HTTP request?

Given your misunderstanding of sockets_ and that you have "www.host.com", 8080 in your question I believe you looking for some web page pulled from www.host.com:8080 via SOCKS proxy. In this case you don't need to reinvent the wheel and use cURL: see How to use a SOCKS 5 proxy with cURL?

If my hunch was wrong and you really need a stream through SOCKS proxy then you need some external library which will do it for you. There no standard PHP extension which will do this for you. You may look at https://github.com/clue/php-socks to get data streams over SOCKS.

like image 175
Vladimir Bashkirtsev Avatar answered Nov 18 '22 11:11

Vladimir Bashkirtsev