# 公开 URL
<subtitle>获取沙箱的公开 URL，连接沙箱内运行的服务。</subtitle>

每个沙箱都可以通过公开 URL 访问，这让您可以暴露并连接到其内部运行的服务。本页介绍如何获取该 URL、连接到沙箱内的服务器，以及自定义服务收到的 `Host` 头。

要控制沙箱的出站互联网访问，请参阅 [网络访问](/docs/agent-sandbox/network/internet-access.md)。要在公开 URL 上要求身份验证，请参阅 [限制公开访问](/docs/agent-sandbox/network/restrict-public-access.md)。

## 沙箱公开 URL

每个沙箱都有一个公开 URL，可用于访问沙箱内运行的服务。

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# 获取 host 时始终需要传入端口号
host = sandbox.get_host(3000)
print(f'https://{host}')
```

上面的代码将打印类似如下内容：

```bash
https://3000-<sandbox-id>.cn-wlcb.sandbox.ucloudai.com
```

host 最左侧的第一部分是我们传给方法的端口号。

## 连接到沙箱内运行的服务器

您可以在沙箱内启动服务器，并使用上面的方法连接到它。

在此示例中，我们将启动一个简单的 HTTP 服务器，它监听 3000 端口，并返回服务器启动所在目录的内容。

```python
import requests
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# 在沙箱内启动一个简单的 HTTP 服务器
process = sandbox.commands.run("python -m http.server 3000", background=True)
host = sandbox.get_host(3000)
url = f"https://{host}"
print('Server started at:', url)

# 从沙箱内的服务器获取数据
response = requests.get(url)
data = response.text
print('Response from server inside sandbox:', data)

# 杀死沙箱内的服务器进程
process.kill()
```

输出将类似如下：

```bash
Server started at: https://3000-<sandbox-id>.cn-wlcb.sandbox.ucloudai.com
Response from server inside sandbox: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
<li><a href=".bash_logout">.bash_logout</a></li>
<li><a href=".bashrc">.bashrc</a></li>
<li><a href=".profile">.profile</a></li>
</ul>
<hr>
</body>
</html>
```

## 遮蔽请求 Host 头

您可以使用 `mask_request_host` 选项自定义发送到沙箱内运行的服务的 `Host` 头。当您的应用程序需要特定的 host 格式时，这很有用。

```python
from ucloud_sandbox import Sandbox

# 创建带有自定义 host 遮蔽的沙箱
sandbox = Sandbox.create(
    network={
        "mask_request_host": "localhost:${PORT}"
    }
)

# ${PORT} 变量将被替换为实际的端口号
# 发往沙箱的请求的 Host 头将被设置为，例如：localhost:8080
```

遮蔽中的 `${PORT}` 变量将自动替换为所请求服务的实际端口号。
