请教在webman中如何获取服务器本身的IP地址

euii

问题描述

请教在webman中如何获取服务器本身的IP地址?我使用了 $_SERVER['SERVER_ADDR' ] 会报错,说没有这个属性。
那么正确的获取服务器本身的IP的方法是什么呢?现在我没办法,直接硬编码了。

public function share($data): array {

        $token = Redis::hGet(config('weibo.redis_key'), 'access_token');
        $client = new Client();
        try {
            $response = $client->request('POST', config('weibo.share_url'), [
                'form_params' => [
                    'access_token' => $token,
                    'status' => $data['content'],
                    'rip' => '192.168.1.1'
                ]
            ])->getBody()->getContents();
            return json_decode($response, true);
        } catch (GuzzleException $e) {
            throw new BizException(ErrorCode::WEIBO_ERR_CODE, ['message' => $e->getMessage()]);
        }
    }

现在按 nitron 建议,我把rip部分换成 'rip' => request()->getLocalIp() , 执行后提示
Error: Call to a member function getLocalIp() on null

上述代码是在redis-queue里调用的

class ShareWeiboSend implements Consumer
{

    /**
     * @Inject
     * @var WeiBoService
     */
    private $weiBoService ;

    // 要消费的队列名
    public $queue = 'share_weibo';

    // 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    public function consume($data) {

        $content['content'] = $this->weiBoService->makeShareContent($data);
        try {
            $this->weiBoService->share($content);
        } catch (BizException $e) {
            Log::error($e->getMessage());
        }
    }

}
1015 4 1
4个回答

nitron
  • euii 2022-12-21

    可惜我并不是在Request中,我是一个队列任务由服务器端直接运行,是远端的API要求传一个IP地址。

  • euii 2022-12-21

    文档里有这一句话,我试试看:
    有时候我们想在其它类中获取当前请求的$request对象,这时候我们只要使用助手函数request()即可;

  • euii 2022-12-21

    我试过了还是不行,会报错

  • euii 2022-12-21

    Error: Call to a member function getLocalIp() on null

不败少龙

request()->getLocalIp();

  • euii 2022-12-21

    不行的,报了这个错误 Error: Call to a member function getLocalIp() on null

  • 不败少龙 2022-12-21

    框架升级试一下

  • euii 2022-12-21

    升级了,还是不行的,问题里的函数是在redis-queue里调用的,是不是这时候是不生产request对象的。

mosquito

我是这样获取服务器公网IP的 shell_exec('curl ifconfig.me')

  • euii 2022-12-21

    谢谢,直接执行shell命令,这个办法可行的。

as5739

内网ip可以用 getHostByName(getHostName())

年代过于久远,无法发表回答
🔝