Use the GetBucketLocation API to retrieve the region where an OSS bucket resides. The API returns a region ID string such as cn-hangzhou. For a full list of valid region IDs, see Regions and endpoints.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket
The
oss:GetBucketLocationpermission. For more information, see Attach a custom policy to a RAM userThe OSS C++ SDK installed and initialized
Usage notes
This example uses the public endpoint of the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead.
To create an OssClient instance using a custom domain name or Security Token Service (STS), see Create an OSSClient instance.
Get the bucket region
The following example initializes an OssClient, calls GetBucketLocation, and prints the returned region ID.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Specify the endpoint of any OSS-supported region.
Example: https://oss-cn-hangzhou.aliyuncs.com */
std::string Endpoint = "yourEndpoint";
/* Specify the region where the bucket resides.
Example: cn-hangzhou */
std::string Region = "yourRegion";
/* Specify the bucket name. */
std::string BucketName = "yourBucketName";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Load access credentials from environment variables.
Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Retrieve the bucket region. */
GetBucketLocationRequest request(BucketName);
auto outcome = client.GetBucketLocation(request);
if (outcome.isSuccess()) {
/* outcome.result().Location() returns a region ID such as "cn-hangzhou". */
std::cout << "GetBucketLocation succeeded. Location: "
<< outcome.result().Location() << std::endl;
} else {
std::cout << "GetBucketLocation failed."
<< " Code: " << outcome.error().Code()
<< " Message: " << outcome.error().Message()
<< " RequestId: " << outcome.error().RequestId()
<< std::endl;
ShutdownSdk();
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}Replace the following placeholders before running the code:
| Placeholder | Description | Example |
|---|---|---|
yourEndpoint | The endpoint of the region where the bucket resides | https://oss-cn-hangzhou.aliyuncs.com |
yourRegion | The region ID of the bucket | cn-hangzhou |
yourBucketName | The name of the bucket | my-bucket |
References
For the complete sample code, see GitHub sample.
For API details, see GetBucketLocation.