gpt4 book ai didi

C: 我可以使用 libssh 转发外部应用程序的端口吗?

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:40 24 4
gpt4 key购买 nike

我正在我的应用程序中为 xen VM 实现 VNC 连接。为了连接,我必须转发端口,因为 XenServer 只接受本地连接。我是这样做的:

ssh -L 5903:localhost:5903 root@192.168.1.4

之后可以将我的 VNC 连接到具有相应端口的本地主机。但是我必须经常重新连接到不同的主机,并且使用 bash 不是一个好主意,因为我也有一个 Windows 构建。安装 ssh-client 并不总是可行的。
我读了http://api.libssh.org/stable/libssh_tutor_forwarding.html并试图测试它。

 ssh_channel forwarding_channel;        
forwarding_channel = ssh_channel_new(session);
int rc = channel_open_forward(forwarding_channel,
"192.168.1.4", 5903,
"localhost", 5903);
if (rc != SSH_OK)
{
ssh_channel_free(forwarding_channel);
return rc;
}
for(;;)
{
usleep(100000);
}

根据状态创建隧道本身。但是我看不到通过 netstat 监听的端口。我做错了什么,这有可能吗?

更新:

这是使用 libssh 似乎可以正常工作的结果代码

int32_t forward_port (ssh_session session, char *remote_host, int32_t remote_port, int32_t local_port)
{
int32_t server_sock = 0;
int32_t client_sock = -1;
struct sockaddr_in client_name;
socklen_t client_name_len = sizeof client_name;
char buf[4096] = {0};
server_sock = server_startup(local_port);
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if (client_sock == -1)
{
perror("Error on accept");
return SSH_ERROR;
}
int32_t client_port = ntohs(client_name.sin_port);
int32_t size_recv, nwritten, nread = 0;
uint8_t data[4096];
fcntl(client_sock, F_SETFL, O_NONBLOCK);
/* */
ssh_channel forwarding_channel;
forwarding_channel = ssh_channel_new(session);
int rc = channel_open_forward(forwarding_channel,
remote_host, remote_port,
"127.0.0.1", client_port);
if (rc != SSH_OK)
{
ssh_channel_free(forwarding_channel);
close(client_sock);
close(server_sock);
return rc;
}
while(!ssh_channel_is_eof (forwarding_channel))
{
if((size_recv = recv(client_sock, data, sizeof data, MSG_DONTWAIT) ) < 0)
{
if((nread = ssh_channel_read_nonblocking(forwarding_channel, data, sizeof data, 0))>0)
{
if(write(client_sock,data,nread)<0)
{
perror("Error writing to socket");
close(client_sock);
close(server_sock);
ssh_channel_free(forwarding_channel);
return SSH_ERROR;
}
}

}
else if (!size_recv)
{
puts("Local client disconnected, exiting");
goto exit;
}
nwritten = channel_write(forwarding_channel, data, size_recv);
if (size_recv != nwritten)
{
ssh_channel_free(forwarding_channel);
return SSH_ERROR;
}
}
exit:
close(client_sock);
close(server_sock);
ssh_channel_free(forwarding_channel);
return SSH_OK;
}

最佳答案

ssh_channel_open_forward 文档

## Warning ##
This function does not bind the local port and does not automatically forward the content of a socket to the channel. You still have to use channel_read and channel_write for this.

关于C: 我可以使用 libssh 转发外部应用程序的端口吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com