php - 无法从托管在 GODADDY 上的站点获取机器的本地 IP 地址

标签 php linux ip-address

嗨,我正在尝试获取访问我们内部门户的机器的本地 IP 地址,我需要 IP 192.168.xx.xx,我尝试使用可能的解决方案,例如

$myIp = getHostByName(getHostName());    
$_SERVER['REMOTE_ADDR']     
$_SERVER['REMOTE_HOST']

function getLocalIP(){
    exec("ipconfig /all", $output);
        foreach($output as $line){
            if (preg_match("/(.*)IPv4 Address(.*)/", $line)){
                $ip = $line;
                $ip = str_replace("IPv4 Address. . . . . . . . . . . :","",$ip);
                $ip = str_replace("(Preferred)","",$ip);
            }
        }
    return $ip;
}

甚至还有一些来自引用的解决方案

How do I get the local IP address of the server using PHP? , how to get local computer ip address in php , Get Local Machine IP Address in PHP

但是没有任何方法可以得到所需的解决方案?有什么建议吗?

最佳答案

通常,您将无法检索位于 NAT 路由器/防火墙后面的任何计算机的本地 ip 地址,尤其是在服务器上运行的 PHP 时尤其如此,因此上面的代码会找到服务器的ip。

但是,您可以使用 Javascript 和 webRTC 中的一项功能来显示门户访问者的本地 IP 地址。如果需要,可以使用 Ajax 将其结果传递给 PHP。几周前我在调查连接问题时发现了这一点——我访问的一个站点显示了我的公共(public)和本地 IP 地址。在查看源代码并进行进一步研究后,我将以下小函数放在一起 - 也许它可能有用。

<?php

?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Get Local IP address</title>
        <script>
            const rtcpip=function( server, callback ){
                /* 
                    https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel
                    https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer
                */
                let debug=true;

                let oList={
                    google1:'stun1.l.google.com:19302',
                    google2:'stun2.l.google.com:19302',
                    google3:'stun3.l.google.com:19302',
                    google4:'stun4.l.google.com:19302',
                    kundenserver:'stun.kundenserver.de:3478',
                    mozilla:'stun.services.mozilla.com:3478',
                    notts:'stun.nottingham.ac.uk:3478'
                };
                const getserver=function(){
                    return oList.hasOwnProperty( server ) ? oList[ server ] : oList.mozilla;
                };

                let duplicates={};
                let stunsvr=getserver();
                let RTCPeerConnection=window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
                let oConstraints={ optional: [ { RtpDataChannels: true } ] };
                let oServers = { iceServers: [ { urls: 'stun:' + stunsvr } ] };

                const info=function(m){
                    if( arguments.length==1 && debug )console.info(m);
                    if( arguments.length==2 && debug )console.info(m,arguments[1]);
                };
                const candidatehandler=function( candidate ){
                    info( candidate );
                    let regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
                    let addr = regex.exec( candidate )[1];
                    if( duplicates[ addr ] === undefined ) callback( addr );
                    duplicates[ addr ] = true;
                };
                const icelistener=function( oIce ){
                    if( oIce.candidate ) candidatehandler.call( this, oIce.candidate.candidate );
                };
                const icedclistener=function(e){
                    let oChan=e.channel;
                        oChan.addEventListener( 'open', function( evt ){ info( evt ) }, false );
                        oChan.addEventListener( 'message', function( evt ){ info( evt.data ) }, false );
                        oChan.addEventListener( 'close', function( evt ){ info( evt ) }, false );
                };
                const icecslistener=function(e){
                    info( 'connectionstatechange: %o',e );
                };
                const icenegotiate=function( e ){
                    info( 'icenegotiate: %o',e );
                };
                const icesignalchange=function(e){
                    info( 'icesignalchange: %o',e );
                };
                const icetrack=function(e){
                    info( 'icetrack: %o',e );
                }

                info( 'STUN Server: %s', stunsvr );

                let rtcp=new RTCPeerConnection( oServers, oConstraints );

                    rtcp.addEventListener( 'icecandidate', icelistener, false );
                    rtcp.addEventListener( 'datachannel', icedclistener, false );
                    rtcp.addEventListener( 'iceconnectionstatechange', icecslistener, false );
                    rtcp.addEventListener( 'negotiationneeded', icenegotiate, false );
                    rtcp.addEventListener( 'signalingstatechange', icesignalchange, false );
                    rtcp.addEventListener( 'track', icetrack, false );
                    rtcp.createDataChannel( 'rtcpip' );         

                    rtcp.createOffer().then( function( offer ){ 
                        return rtcp.setLocalDescription( offer )
                    } ).then( function(){
                        let lines = rtcp.localDescription.sdp.split( String.fromCharCode( 10 ) );
                            lines.forEach( function( line ){
                                if( ~line.indexOf( 'a=candidate:' ) ) candidatehandler.call( this, line );
                            });
                    });
            };

            const create=function(t, a, p){
                try{
                    var el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
                    for( var x in a ) if( a.hasOwnProperty( x ) && x!=='innerHTML' ) el.setAttribute( x, a[ x ] );
                    if( a.hasOwnProperty('innerHTML') ) el.innerHTML=a.innerHTML;
                    if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
                    return el;
                }catch( err ){
                    console.warn( err.message );
                }
            };

            const ipcallback=function( ip ){
                try{
                    let type=false;

                    let ipv4=ip.split('.');
                    let ipv6=ip.split(':');

                    if( ipv4.length==4 ){
                        let local=( ipv4[0] == 10 || ( ipv4[0]==172 && ( ipv4[1]>=16 &&ipv4[1]<=31 ) ) || ( ipv4[0]==192 && ipv4[1]==168 ) );
                        create( null,{ innerHTML:ip + ( local ? ' - Private' : ' - Public' ) }, document.getElementById( 'ip' ) );                  
                    }

                    if( ipv6.length > 1 ){
                        switch( ipv6[0] ){
                            case 'FE80':type='Link-Local';break;
                            case 'FEC0':type='site-local';break;
                            case '3FFE':type='global';break;
                            case '2002':type='global 6to4';break;
                            default:type='IPV6';break;
                        }
                        create( null,{ innerHTML:ip + ' ' + type }, document.getElementById( 'ip' ) );
                        /*
                            you can use this callback to pass the ip address information on to a php script
                            or do something more interesting
                        */
                    }
                }catch( err ){
                    console.info( err.message )
                }
            }


            rtcpip.call( this, 'google1', ipcallback );
        </script>
        <style>
            body{display:flex;flex-direction:column;justify-content:center;align-items:center;height:100vh;width:100%;padding:0;margin:0;font-family:calibri,verdana,arial;font-size:1rem;}
            #ip{display:flex;align-items:center;justify-content:center;flex-direction:column;width:50%;min-height:5rem;height:auto;box-sizing:border-box;border:2px dashed rgba(133,133,133,0.25);border-radius:1rem;color:rgba(133,133,133,0.95);box-shadow: 0 10px 25px rgba(133,133,133,0.95);text-align:center;margin:0 auto;float:none;background:whitesmoke}
        </style>
    </head>
    <body>
        <div id='ip'></div>
    </body>
</html>

关于php - 无法从托管在 GODADDY 上的站点获取机器的本地 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52289423/

相关文章:

php - 将数组对象转换为字符串并分隔值

php - Apache 缓冲区溢出,虚拟主机过多

linux - 在 Linux 上使用 8 位颜色正确显示 Qt Gui。对话框中的点

php - Maxmind Geolitecity 数据库中的 IP 地址表示

c# - maskedTextBox C# 中的 IP 地址验证

php - PHP 中机器的 IP 地址给出::1 但为什么呢?

php - yii 组件 : events and behaviors?

php - PDO插入不起作用,但其他可以

linux - 我想在 vmware 工作站中安装 centos 6.6 和 centos 6.6 最小服务器有什么区别?

linux - 相同的 QFont 配置导致嵌入式 Linux 和 Linux Ubuntu 之间的字体不同