> ## Documentation Index
> Fetch the complete documentation index at: https://ppio.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 联网功能

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>在运行本文档中的示例代码前，请确保您已正确配置环境变量，详情请参考 <a href="/sandbox/get-start#配置环境变量">配置环境变量</a>。</Note>;
  }
};

每个沙箱都可以访问互联网，并且可被公共 URL 访问其上运行的服务。

<SandboxConfigHint />

## 沙箱公共 URL

每个沙箱都能提供公共 URL，用于访问沙箱内运行的服务。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={null}
  import { Sandbox } from 'ppio-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // 您需要传入一个端口号来获取公共 URL。
  const host = sandbox.getHost(3000)
  console.log(`https://${host}`)

  // 输出示例：
  // https://3000-icl2ke7w1grxep2o771m1-abf219fd.sandbox.ppio.cn

  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  from ppio_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create()

  # 您需要传入一个端口号来获取公共 URL。
  host = sandbox.get_host(3000)
  print(f'https://{host}')

  # 输出示例：
  # https://3000-ik56flymp4xczmvmt97lk-abf219fd.sandbox.ppio.cn

  sandbox.kill()
  ```
</CodeGroup>

## 访问沙箱内运行的服务

您可以在沙箱内启动服务并通过一个公共 URL 访问它。

在这个示例中，我们将启动一个简单的 HTTP 服务器，监听端口 3000，并返回启动服务器的目录信息。

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={null}
  import { Sandbox } from 'ppio-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // 启动一个简单的 HTTP 服务器。
  const commandHandle = await sandbox.commands.run('python -m http.server 3000', { background: true })
  const host = sandbox.getHost(3000)
  const url = `https://${host}`
  console.log('Server started at:', url)

  // 从服务器获取数据。
  const response = await fetch(url);
  const data = await response.text();
  console.log('Response from server inside sandbox:', data);

  // 终止服务器进程。
  await commandHandle.kill()

  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  from ppio_sandbox.code_interpreter 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 = sandbox.commands.run(f"curl {url}")
  data = response.stdout
  print("Response from server inside sandbox:", data)

  # 终止服务器进程。
  process.kill()

  sandbox.kill()
  ```
</CodeGroup>
