通过bind绑定本机地址(local addr)以及端口(local port), 实现从本机端口(local port)发送以及监听;
通过connect指定目的地址(dst addr)以及目的端口(dst port), 实现目标地址的绑定;
dst_addr.sin_family = AF_INET;
dst_addr.sin_addr.s_addr = inet_addr(dstIP);
dst_addr.sin_port = htons(dstPort);
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = inet_addr(localIP);
local_addr.sin_port = htons(localPort);
if(bind(m_socket, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0) {
LOG(ERROR) << "bind local address error, ";
return;
}
if(connect(m_socket, (struct sockaddr*)&dst_addr,sizeof(dst_addr)) < 0) {
LOG(ERROR) << "connect to server error";
return;
}
实现效果
localaddr(192.168.0.1) local port (8888)
dstaddr(192.168.0.2) local port(9999)
192.168.0.1:8888 -> 192.168.0.2:9999 发送消息