adb 修改 支持任意 ip 连接 默认5037 和 forward socket 端口

项目需要使用 adb socket
adb 的默认端口是 5037 仅支持本地 127.0.0.1 连接
后分析源码后发现只需修改一处,即可接受所有连接,关键代码如下:
android/system/core/libcutils/socket_loopback_server.c

/* libs/cutils/socket_loopback_server.c
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License"); 
** you may not use this file except in compliance with the License. 
** You may obtain a copy of the License at 
**
**     http://www.apache.org/licenses/LICENSE-2.0 
**
** Unless required by applicable law or agreed to in writing, software 
** distributed under the License is distributed on an "AS IS" BASIS, 
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
** See the License for the specific language governing permissions and 
** limitations under the License.
*/

#include 

#include 
#include 
#include 
#include 
#include 

#define LISTEN_BACKLOG 4

#ifndef HAVE_WINSOCK
#include 
#include 
#include 
#include 
#endif

/* open listen() port on loopback interface */
int socket_loopback_server(int port, int type)
{
    struct sockaddr_in addr;
    size_t alen;
    int s, n;

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    # addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); #//关键位置
    s = socket(AF_INET, type, 0);
    if(s < 0) return -1;

    n = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));

    if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        close(s);
        return -1;
    }

    if (type == SOCK_STREAM) {
        int ret;

        ret = listen(s, LISTEN_BACKLOG);

        if (ret < 0) {
            close(s);
            return -1; 
        }
    }

    return s;
}

只需要修改
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

addr.sin_addr.s_addr = htonl(INADDR_ANY);
之所以这么修改是因为
INADDR_ANY是ANY,是绑定地址0.0.0.0上的监听, 能收到任意一块网卡的连接;
INADDR_LOOPBACK, 也就是绑定地址LOOPBAC, 往往是127.0.0.1, 只能收到127.0.0.1上面的连接请求

修改完成后重新编译 adb 就可以任意 ip 连接了

你可能感兴趣的:(android,C,adb修改,任意ip连接5037)