CoinAnalyzer
CoinAnalyzer

Reputation: 56

Javascript - PHP Websocket - Getting User IP Address

I'm trying to make a game.

However, I can't get the user ip address on the php side.

I am using plain websocket.

I tried the following codes but it doesn't give what I want. The server gives the ip address.

JAVASCRIPT

websocket = new WebSocket("wss://site.com/game_play/"); 
websocket.binaryType = "arraybuffer";
websocket.onopen = function(event) { 
    
    var send = {
        type: "sign",
        oauth: g_oauth,
        room: g_room,
    };
    websocket.send(binary_encode(send));
}
.....

PHP

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
socket_bind($socket, 0, $port);

socket_listen($socket);
.....

APACHE

ProxyPass /game_play/ ws://site.com:8090/server.php
ProxyPassReverse /game_play/ ws://site.com:8090/server.php

socket_getsockname, socket_getpeername

I tried some functions but unsuccessful. Because the server gives the ip address. I am trying to get user ip address.

Upvotes: 0

Views: 403

Answers (1)

jshrc
jshrc

Reputation: 187

According to the docs you may need to use socket_accept() instead of socket_connect():

Note: socket_getsockname() should not be used with AF_UNIX sockets created with socket_connect(). Only sockets created with socket_accept() or a primary server socket following a call to socket_bind() will return meaningful values.

Edit: wrong function called, should be socket_getpeername()

Either way, the second param in socket_getpeername() is passed by reference and will contain the client IP if the socket is good:

<?php 
....
socket_listen($socket);

$address = '';
socket_getpeername($socket, $address); //$address is passed by reference and will contain the remote IP. 

Upvotes: 1

Related Questions