2019년 4월 22일 월요일

[PHP] 현재 사용중인 통신사(ISP)에 맞게 M3U 파일 보여주기.

IPTV를 보기 위해 M3U를 만들었습니다.
회사는 KT, 집은 SK, 본가는 LG 를 씁니다.
그리고 개인 서버에 M3U를 올려 놓고 집이나 휴대폰이나 회사에서 M3U를 가지고 MP3를 볼수 있는 프로그램에 M3U 경로를 지정해 주고 쓰고 있었는데, 통신사 마다 주소를 다르게 쳐주는게 은근 귀찮아서 만들어 봤습니다.
현재 IP를 가지고 통신사 ISP를 추적한후 통신사에 맞는 M3U파일을 보여 줍니다.
그리고 현재 사용중인 ASUS 공유기 RT-AC88U 에 경우 UDP 프록시 기능이 있어서 이 기능을 사용하면 버퍼링이 좀더 원활해 집니다.
<?php
/**
 * ================================
 * 2017/07/20
 * By CodeH
 * haesup@gmail.com
 * http://codeh.kr
 * ================================
 *
 * IP로 통신사 ISP 를 판단해서 각 통신사에 맞는 m3u 파일을 출력해준다.
 *
 *
 * ---------------------
 * 주소창에 인수로 옵션을 지정
 * ---------------------
 * 옵션명 : r=[숫자or아이피주소]
 * ?r=192.168.0.1 과 같이 값을 넣으면 Asus 라우터에 맞게 M3U 파일 앞에 라우터 UDP 프록시 주소를 넣어준다.
 * 0,1,2 를 넣으면 192.168.?.1 로 지정된다.
 *
 * 옵션명 : isp=[isp이름]
 * isp를 강제로 지정 한다. local / sk / lg / kt
 *
 * 옵션명 : p=port
 * 라우터에 Proxy 포트를 지정.. 기본 4000
 *
 * 옵션명 : d=1
 * 디버그 모드
 * ---------------------
 */

if ($_GET[d] == 1) {
    $DebugMode = true;
}
if ($_GET[r] <> "") {
    $RouterProxyIP = $_GET[r];
    //라우터 옵션에 IP 주소 다 쳐주는거 번거로우니 일반적으로 많이 쓰는 IP 대역 0,1,2 을 넣으면 자동으로 IP 대역을 만들어 준다.
    if ($RouterProxyIP == 0) $RouterProxyIP = "192.168.0.1";
    if ($RouterProxyIP == 1) $RouterProxyIP = "192.168.1.1";
    if ($RouterProxyIP == 2) $RouterProxyIP = "192.168.2.1";
    if ($DebugMode) echo ("RouterProxyIP ON / in Router Address : " . $RouterProxyIP . "<BR>");
}

// 포트값을 넣어주면 해당 포트를 사용하고... 안넣어주면 기본 포트인 4000번을 사용 한다.
if ($_GET[p] <> "") {
    $RouterProxyPort = $_GET[p];
}
else {
    $RouterProxyPort = "4000";
}

if ($_GET[isp] <> "") {
    $ISP  = $_GET[isp];
    if ($DebugMode) echo ("in isp  : " . $ISP . "<BR>");
}


    $IP = $_SERVER['REMOTE_ADDR'];
    //$IP = "164.124.101.2";  //LG DNS
    //$IP = "203.248.252.2";  //LG DNS
    //$IP = "210.220.163.82";  //SK DNS
    //$IP = "219.250.36.130";  //SK DNS
    //$IP = "168.126.63.1";  //KT DNS
    //$IP = "168.126.63.2";  //KT DNS

if ($DebugMode) echo ("Client IP : " . $IP . "<BR>");


//-----------------------------------------------------------------------------
//Local 인지 검사.

if ($ISP == "") {
    $IP_Parts = explode(".", $IP);
    $IP_Head = $IP_Parts[0] . "." . $IP_Parts[1];
    if ($DebugMode) echo ("IP Head : " . $IP_Head . " == (192.168)<BR>");
    if ($IP_Head == "192.168") {
        $ISP = "Local";
    }

    $IP_Head = $IP_Parts[0] . "." . $IP_Parts[1] . "." . $IP_Parts[2] . ".0" ; 
}
//-----------------------------------------------------------------------------

if ($ISP == "") {
    $foundISP = "";
    $foundFile = false;


    $fp = fopen("./ip.txt", 'r');
    if($fp) {
        while(!feof($fp)) {
            $readstr = fgets($fp,1024);
            $readval = explode(",", $readstr);                        
            $IP_Parts = explode(".", $readval[0]);

            $IP_Head_File = $IP_Parts[0] . "." . $IP_Parts[1] . "." . $IP_Parts[2] . ".0" ; 

            //if ( $readval[0] == $IP ) {
            if ( $IP_Head == $IP_Head_File ) {
                $foundFile = true;
                $foundISP = $readval[1];
                $ISP = $foundISP;
                if ($DebugMode) echo ($ISP . "<BR>");
            }
        }
    }
    else {
        if ($DebugMode) echo ("[no file]");
    }

    if ($foundISP == "") {
        if ($DebugMode) echo ("[no found ip from file]");
    }
    else {
        if ($DebugMode) echo ($foundISP);
    }

    if ($DebugMode) echo ("[end]");
    fclose($fp);
}
//-----------------------------------------------------------------------------

if ($foundISP == "" && $ISP == "") {
    $User_Agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0';
    $Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
    $Accept_Language = 'en-US,en;q=0.5';
    $Referer = 'http://whatismyipaddress.com/';
    $Connection = 'keep-alive';

    $HTML = file_get_contents("http://whatismyipaddress.com/ip/$IP", false, stream_context_create(array('http' => array('method' => 'GET', 'header' => "User-Agent: $User_Agent\r\nAccept: $Accept\r\nAccept-Language: $Accept_Language\r\nReferer: $Referer\r\nConnection: $Connection\r\n\r\n"))));

    preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s', $HTML, $Matches, PREG_SET_ORDER);

    $ASN = $Matches[3][2];
    $ISP = $Matches[4][2];
    $City = $Matches[11][2];
    $State = $Matches[10][2];
    $ZIP = $Matches[15][2];
    $Country = $Matches[9][2];

    if ($DebugMode) echo $ISP . "<BR>";
    if ($DebugMode) echo $ASN . "<BR>";
}


//-----------------------------------------------------------------------------
//echo ("ISP: " . $ISP . "<BR>");
$ISP = preg_replace('/\r\n|\r|\n/','',$ISP);    //개행문자 제거

if ($ISP == "local" || $ISP == "" || $ISP == "Local") {
    if ($DebugMode)  echo "Local KT";
    //if (!$DebugMode) echo include("../h/kt_router.m3u");
    if ($RouterProxyIP == "" ) $RouterProxyIP = "192.168.0.1";  //서버가 있는곳은 KT에 라우터 Proxy를 항상 쓰니 따로 라우터 옵션을 안줘도 그냥 라우터 Proxy 값을 적용해준다.
    if (!$DebugMode) Show_M3U("../h/kt.m3u", $RouterProxyIP, $RouterProxyPort);
}
elseif ($ISP == "kt" || $ISP == "Korea Telecom" || $ASN == 4766) {
    if ($DebugMode)  echo "KT";
    //if (!$DebugMode) echo include("../h/kt.m3u");
    if (!$DebugMode) Show_M3U("../h/kt.m3u", $RouterProxyIP, $RouterProxyPort);
}
elseif ($ISP == "sk" || $ISP == "SK Broadband" || $ISP == "SK Telecom" || $ASN == 9318 || $ASN == 9644) {
    if ($DebugMode)  echo "SK";
    //if (!$DebugMode) echo include("../h/sk.m3u");
    if (!$DebugMode) Show_M3U("../h/sk.m3u", $RouterProxyIP, $RouterProxyPort);
}
elseif ($ISP == "lg" || $ISP == "LG DACOM Corporation" || $ASN == 3786 || $ISP == "Lg Powercomm" || $ASN == 17858) {
    if ($DebugMode)  echo "LG";
    //if (!$DebugMode) echo include("../h/lg.m3u");
    if (!$DebugMode) Show_M3U("../h/lg.m3u", $RouterProxyIP, $RouterProxyPort);
}
else {
    echo "unknown isp!";   
    echo ("ISP: " . $ISP . "<BR>");
    $ISP = "";
}

?>


<?php 
/*
<body>
    <table align="center">
        <tr><td>IP :</td><td><?php echo $IP;?></td></tr>
        <tr><td>ASN :</td><td><?php echo $ASN;?></td></tr>
        <tr><td>ISP :</td><td><?php echo $ISP;?></td></tr>
        <tr><td>City :</td><td><?php echo $City;?></td></tr>
        <tr><td>State :</td><td><?php echo $State;?></td></tr>
        <tr><td>Zipcode :</td><td><?php echo $ZIP;?></td></tr>
        <tr><td>Country :</td><td><?php echo $Country;?></td></tr>
    </table>
</body>
*/


if ( $foundISP == "" && $ISP <> "Local" && $_GET[isp] == "") {
    if ($DebugMode) echo ("<BR>" . "[W]");
    $fp = fopen("./ip.txt", 'ab');
    //fwrite($fp, $IP . "," . $ISP . "\r\n");
    fwrite($fp, $IP_Head . "," . $ISP . "\r\n");    
    fclose($fp);
}

function Show_M3U($filename, $RouterProxyIP, $RouterProxyPort){
    //echo include($filename);
    $fp = fopen( $filename , 'r');

    if($fp) {
        while(!feof($fp)) {
            $readstr = fgets($fp,1024);
            //str_replace("rtp://", "http://192.168.0.1:4000/rtp/", $readstr) ;
            $changeStr = $readstr;
            if ($RouterProxyIP <> "") {
                $changeStr = str_replace("rtp://", "http://" . $RouterProxyIP . ":" . $RouterProxyPort . "/rtp/", $changeStr) ;    
                $changeStr = str_replace("udp://", "http://" . $RouterProxyIP . ":" . $RouterProxyPort . "/udp/", $changeStr) ;    
            }

            echo $changeStr;
        }
        fclose($fp);
    }
}

?>
그리고 부수적으로 IP를 가지고 ISP를 검색 할때 조금 시간이 걸려서 그냥 TXT 파일에 이전 IP를 저장 하는 기능을 추가 했습니다. DB 까지는 구지 사용할 필요가 없을거 같고..이 자료 퍼가실때 DB 설정 까지 하시긴 번거로우실테니 그냥 TXT 파일을 사용 했습니다.

별거 아닌 코드지만 그래도 처음부터 만들긴 시간이 걸리니 그냥 참고 하시기 바랍니다.

댓글 없음:

댓글 쓰기