Android多个网络连接

InetAddress.clearDnsCache();
// Must flush socket pool as idle sockets will be bound to previous network and may
// cause subsequent fetches to be performed on old network.
NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
return true;
} else {
return false;
}
}

2. 在 setProcessDefaultNetwork 的时候,HttpProxy,DNS 都会使用当前网络的配置,再来看一下 NetworkUtils.bindProcessToNetwork
/frameworks/base/core/java/android/net/NetworkUtils.bindProcessToNetwork 其实是直接转到了 /system/netd/client/NetdClient.cpp 中

int setNetworkForTarget(unsigned netId, std::atomic_uint* target) {
if (netId == NETID_UNSET) {
*target = netId;
return 0;
}
// Verify that we are allowed to use |netId|, by creating a socket and trying to have it marked
// with the netId. Call libcSocket() directly; else the socket creation (via netdClientSocket())
// might itself cause another check with the fwmark server, which would be wasteful.
int socketFd;
if (libcSocket) {
socketFd = libcSocket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
} else {
socketFd = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
}
if (socketFd < 0) {
return -errno;
}
int error = setNetworkForSocket(netId, socketFd);
if (!error) {
*target = netId;
}
close(socketFd);
return error;
}

extern “C” int setNetworkForSocket(unsigned netId, int socketFd) {
if (socketFd < 0) {
return -EBADF;
}
FwmarkCommand command = {FwmarkCommand::SELECT_NETWORK, netId, 0};
return FwmarkClient().send(&command, socketFd);
}

extern “C” int setNetworkForProcess(unsigned netId) {
return setNetworkForTarget(netId, &netIdForProcess);
}

3. 客户端发送 FwmarkCommand::SELECT_NETWORK 通知服务端处理,代码在 /system/netd/server/FwmarkServer.cpp

int FwmarkServer::processClient(SocketClient* client, int* socketFd) {
// …
Fwmark fwmark;
socklen_t fwmarkLen = sizeof(fwmark.intValue);
if (getsockopt(*socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen) == -1) {
return -errno;
}

switch (command.cmdId) {
// …
case FwmarkCommand::SELECT_NETWORK: {
fwmark.netId = command.netId;
if (command.netId == NETID_UNSET) {
fwmark.explicitlySelected = false;
fwmark.protectedFromVpn = false;
permission = PERMISSION_NONE;
} else {
if (int ret = mNetworkController->checkUserNetworkAccess(client->getUid(),
command.netId)) {
return ret;
}
fwmark.explicitlySelected = true;
fwmark.protectedFromVpn = mNetworkController->canProtect(client->getUid());
}
break;
}
// …
}

fwmark.permission = permission;

if (setsockopt(*socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue,
sizeof(fwmark.intValue)) == -1) {
return -errno;
}

return 0;
}

union Fwmark {
uint32_t intValue;
struct {
unsigned netId : 16;
bool explicitlySelected : 1;
bool protectedFromVpn : 1;
Permission permission : 2;
};
Fwmark() : intValue(0) {}
};

最后其实只是给 socketFd 设置了 mark,为什么这样就可以达到使用特定网络的目的呢。这里的实现原理大致为:
1. 该进程在创建socket时(app首先调用setProcessDefaultNetwork()),android底层会利用setsockopt函数设置该socket的SO_MARK为netId(android有自己的管理逻辑,每个Network有对应的ID),以后利用该socket发送的数据都会被打上netId的标记(fwmark 值)。
2. 利用策略路由,将打着netId标记的数据包都路由到指定的网络接口,例如WIFI的接口wlan0。
Linux 中的策略路由暂不在本章展开讨论,这里只需要了解通过这种方式就能达到我们的目的。

Hook socket api

也就是说只要在当前进程中利用setsockopt函数设置所有socket的SO_MARK为netId,就可以完成所有的请求都走特定的网络接口。

1. 先来看一下 /bionic/libc/bionic/socket.cpp

int socket(int domain, int type, int protocol) {
return __netdClientDispatch.socket(domain, type, protocol);
}

2. /bionic/libc/private/NetdClientDispatch.h

struct NetdClientDispatch {
int (accept4)(int, struct sockaddr, socklen_t*, int);
int (connect)(int, const struct sockaddr, socklen_t);
int (*socket)(int, int, int);
unsigned (*netIdForResolv)(unsigned);
};

extern LIBC_HIDDEN struct NetdClientDispatch __netdClientDispatch;

3. /bionic/libc/bionic/NetdClientDispatch.cpp

extern “C” __socketcall int __accept4(int, sockaddr*, socklen_t*, int);
extern “C” __socketcall int __connect(int, const sockaddr*, socklen_t);
extern “C” __socketcall int __socket(int, int, int);

static unsigned fallBackNetIdForResolv(unsigned netId) {
return netId;
}

// This structure is modified only at startup (when libc.so is loaded) and never
// afterwards, so it’s okay that it’s read later at runtime without a lock.
LIBC_HIDDEN NetdClientDispatch __netdClientDispatch attribute((aligned(32))) = {
__accept4,
__connect,
__socket,
fallBackNetIdForResolv,
};

4. /bionic/libc/bionic/NetdClient.cpp

template
static void netdClientInitFunction(void* handle, const char* symbol, FunctionType* function) {
typedef void (InitFunctionType)(FunctionType);
InitFunctionType initFunction = reinterpret_cast(dlsym(handle, symbol));
if (initFunction != NULL) {
initFunction(function);
}
}

static void netdClientInitImpl() {
void* netdClientHandle = dlopen(“libnetd_client.so”, RTLD_NOW);
if (netdClientHandle == NULL) {
// If the library is not available, it’s not an error. We’ll just use
// default implementations of functions that it would’ve overridden.
return;
}
netdClientInitFunction(netdClientHandle, “netdClientInitAccept4”,
&__netdClientDispatch.accept4);
netdClientInitFunction(netdClientHandle, “netdClientInitConnect”,
&__netdClientDispatch.connect);
netdClientInitFunction(netdClientHandle, “netdClientInitNetIdForResolv”,
&__netdClientDispatch.netIdForResolv);
netdClientInitFunction(netdClientHandle, “netdClientInitSocket”, &__netdClientDispatch.socket);
}

static pthread_once_t netdClientInitOnce = PTHREAD_ONCE_INIT;

extern “C” LIBC_HIDDEN void netdClientInit() {
if (pthread_once(&netdClientInitOnce, netdClientInitImpl)) {
__libc_format_log(ANDROID_LOG_ERROR, “netdClient”, “Failed to initialize netd_client”);
}
}

5. /system/netd/client/NetdClient.cpp

extern “C” void netdClientInitSocket(SocketFunctionType* function) {
if (function && *function) {
libcSocket = *function;
*function = netdClientSocket;
}
}

int netdClientSocket(int domain, int type, int protocol) {

总结

本文讲解了我对Android开发现状的一些看法,也许有些人会觉得我的观点不对,但我认为没有绝对的对与错,

一切交给时间去证明吧!愿与各位坚守的同胞们互相学习,共同进步!

ocket;
}
}

int netdClientSocket(int domain, int type, int protocol) {

总结

本文讲解了我对Android开发现状的一些看法,也许有些人会觉得我的观点不对,但我认为没有绝对的对与错,
[外链图片转存中…(img-zOrcch9t-1716051777607)]
一切交给时间去证明吧!愿与各位坚守的同胞们互相学习,共同进步!

  • 30
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值